~ chicken-core (master) /manual/Module (scheme base)
Trap1[[tags: manual]]2[[toc:]]34== Module scheme56This module provides all of CHICKEN's R7RS procedures and macros.7These descriptions are based directly on the ''Revised^7 Report on the8Algorithmic Language Scheme''.910== Expressions1112Expression types are categorized as primitive or derived. Primitive13expression types include variables and procedure calls. Derived14expression types are not semantically primitive, but can instead be15defined as macros. The distinction which R7RS makes between primitive16and derived is unimportant and does not necessarily reflect how it is17implemented in CHICKEN itself.1819=== Primitive expression types2021==== Variable references2223<macro><variable></macro><br>2425An expression consisting of a variable is a variable reference. The26value of the variable reference is the value stored in the location to27which the variable is bound. It is an error to reference an unbound28variable.2930 (define x 28)31 x ===> 283233==== Literal expressions3435<macro>(quote <datum>)</macro><br>36<macro>'<datum></macro><br>37<macro><constant></macro><br>3839(quote <datum>) evaluates to <datum>. <Datum> may be any external40representation of a Scheme object. This notation is used to include41literal constants in Scheme code.4243 (quote a) ===> a44 (quote #(a b c)) ===> #(a b c)45 (quote (+ 1 2)) ===> (+ 1 2)4647(quote <datum>) may be abbreviated as '<datum>. The two notations are48equivalent in all respects.4950 'a ===> a51 '#(a b c) ===> #(a b c)52 '() ===> ()53 '(+ 1 2) ===> (+ 1 2)54 '(quote a) ===> (quote a)55 ''a ===> (quote a)5657Numerical constants, string constants, character constants, and boolean58constants evaluate "to themselves"; they need not be quoted.5960 '"abc" ===> "abc"61 "abc" ===> "abc"62 '145932 ===> 14593263 145932 ===> 14593264 '#t ===> #t65 #t ===> #t66 '#(a 10) ===> #(a 10)67 #(a 10) ===> #(a 10)68 '#u8(64 65) ===> #u8(64 65)69 #u8(64 65) ===> #u8(64 65)7071It is an error to alter a constant (i.e. the value of a literal72expression) using a mutation procedure like set-car! or string-set!.73In the current implementation of CHICKEN, identical constants don't74share memory and it is possible to mutate them, but this may change in75the future.7677==== Procedure calls7879<macro>(<operator> <operand[1]> ...)</macro><br>8081A procedure call is written by simply enclosing in parentheses82expressions for the procedure to be called and the arguments to be83passed to it. The operator and operand expressions are evaluated (in an84unspecified order) and the resulting procedure is passed the resulting85arguments.8687 (+ 3 4) ===> 788 ((if #f + *) 3 4) ===> 128990A number of procedures are available as the values of variables in the91initial environment; for example, the addition and multiplication92procedures in the above examples are the values of the variables + and93*. New procedures are created by evaluating lambda94expressions. Procedure calls may return any number of values (see the95{{values}} procedure [[#control-features|below]]).9697Procedure calls are also called combinations.9899Note: In contrast to other dialects of Lisp, the order of100evaluation is unspecified, and the operator expression and the101operand expressions are always evaluated with the same evaluation102rules.103104Note: Although the order of evaluation is otherwise unspecified,105the effect of any concurrent evaluation of the operator and operand106expressions is constrained to be consistent with some sequential107order of evaluation. The order of evaluation may be chosen108differently for each procedure call.109110Note: In many dialects of Lisp, the empty combination, (), is a111legitimate expression. In Scheme, combinations must have at least112one subexpression, so () is not a syntactically valid expression.113114==== Procedures115116<macro>(lambda <formals> <body>)</macro><br>117118Syntax: <Formals> should be a formal arguments list as described below,119and <body> should be a sequence of one or more expressions.120121Semantics: A lambda expression evaluates to a procedure. The122environment in effect when the lambda expression was evaluated is123remembered as part of the procedure. When the procedure is later called124with some actual arguments, the environment in which the lambda125expression was evaluated will be extended by binding the variables in126the formal argument list to fresh locations, the corresponding actual127argument values will be stored in those locations, and the expressions128in the body of the lambda expression will be evaluated sequentially in129the extended environment. The result(s) of the last expression in the130body will be returned as the result(s) of the procedure call.131132 (lambda (x) (+ x x)) ===> a procedure133 ((lambda (x) (+ x x)) 4) ===> 8134135 (define reverse-subtract136 (lambda (x y) (- y x)))137 (reverse-subtract 7 10) ===> 3138139 (define add4140 (let ((x 4))141 (lambda (y) (+ x y))))142 (add4 6) ===> 10143144<Formals> should have one of the following forms:145146* (<variable[1]> ...): The procedure takes a fixed number of147 arguments; when the procedure is called, the arguments will be148 stored in the bindings of the corresponding variables.149150* <variable>: The procedure takes any number of arguments; when the151 procedure is called, the sequence of actual arguments is converted152 into a newly allocated list, and the list is stored in the binding153 of the <variable>.154155* (<variable[1]> ... <variable[n]> . <variable[n+1]>): If a156 space-delimited period precedes the last variable, then the157 procedure takes n or more arguments, where n is the number of158 formal arguments before the period (there must be at least one).159 The value stored in the binding of the last variable will be a160 newly allocated list of the actual arguments left over after all161 the other actual arguments have been matched up against the other162 formal arguments.163164It is an error for a <variable> to appear more than once in <formals>.165166 ((lambda x x) 3 4 5 6) ===> (3 4 5 6)167 ((lambda (x y . z) z)168 3 4 5 6) ===> (5 6)169170Each procedure created as the result of evaluating a lambda expression171is (conceptually) tagged with a storage location, in order to make eqv?172and eq? work on procedures.173174As an extension to R7RS, CHICKEN also supports "extended" DSSSL style175parameter lists, which allows embedded special keywords. Such a176keyword gives a special meaning to the {{<formal>}} it precedes.177DSSSL parameter lists are defined by the following grammar:178179 <parameter-list> ==> <required-parameter>*180 [#!optional <optional-parameter>*]181 [#!rest <rest-parameter>]182 [#!key <keyword-parameter>*]183 <required-parameter> ==> <ident>184 <optional-parameter> ==> <ident>185 | (<ident> <initializer>)186 <rest-parameter> ==> <ident>187 <keyword-parameter> ==> <ident>188 | (<ident> <initializer>)189 <initializer> ==> <expr>190191When a procedure is applied to a list of arguments, the parameters and arguments are processed from left to right as follows:192193* Required-parameters are bound to successive arguments starting with the first argument. It shall be an error if there are fewer arguments than required-parameters.194* Next, the optional-parameters are bound with the remaining arguments. If there are fewer arguments than optional-parameters, then the remaining optional-parameters are bound to the result of the evaluation of their corresponding <initializer>, if one was specified, otherwise {{#f}}. The corresponding <initializer> is evaluated in an environment in which all previous parameters have been bound.195* If there is a rest-parameter, then it is bound to a list containing all the remaining arguments left over after the argument bindings with required-parameters and optional-parameters have been made.196* If {{#!key}} was specified in the parameter-list, there should be an even number of remaining arguments. These are interpreted as a series of pairs, where the first member of each pair is a keyword specifying the parameter name, and the second member is the corresponding value. If the same keyword occurs more than once in the list of arguments, then the corresponding value of the first keyword is the binding value. If there is no argument for a particular keyword-parameter, then the variable is bound to the result of evaluating <initializer>, if one was specified, otherwise {{#f}}. The corresponding <initializer> is evaluated in an environment in which all previous parameters have been bound.197198Needing a special mention is the close relationship between the199rest-parameter and possible keyword-parameters. Declaring a200rest-parameter binds up all remaining arguments in a list, as201described above. These same remaining arguments are also used for202attempted matches with declared keyword-parameters, as described203above, in which case a matching keyword-parameter binds to the204corresponding value argument at the same time that both the keyword205and value arguments are added to the rest parameter list. Note that206for efficiency reasons, the keyword-parameter matching does nothing207more than simply attempt to match with pairs that may exist in the208remaining arguments. Extra arguments that don't match are simply209unused and forgotten if no rest-parameter has been declared. Because210of this, the caller of a procedure containing one or more211keyword-parameters cannot rely on any kind of system error to report212wrong keywords being passed in.213214It shall be an error for an {{<ident>}} to appear more than once in a215parameter-list.216217If there is no rest-parameter and no keyword-parameters in the parameter-list, then it shall be an error for any extra arguments to be passed to the procedure.218219220Example:221222 ((lambda x x) 3 4 5 6) => (3 4 5 6)223 ((lambda (x y #!rest z) z)224 3 4 5 6) => (5 6)225 ((lambda (x y #!optional z #!rest r #!key i (j 1))226 (list x y z i: i j: j))227 3 4 5 i: 6 i: 7) => (3 4 5 i: 6 j: 1)228229230231==== Conditionals232233<macro>(if <test> <consequent> <alternate>)</macro><br>234<macro>(if <test> <consequent>)</macro><br>235236Syntax: <Test>, <consequent>, and <alternate> may be arbitrary237expressions.238239Semantics: An if expression is evaluated as follows: first, <test> is240evaluated. If it yields a true value (see [[#Booleans|the section241about booleans]] below), then <consequent> is evaluated and its242value(s) is(are) returned. Otherwise <alternate> is evaluated and its243value(s) is(are) returned. If <test> yields a false value and no244<alternate> is specified, then the result of the expression is245unspecified.246247 (if (> 3 2) 'yes 'no) ===> yes248 (if (> 2 3) 'yes 'no) ===> no249 (if (> 3 2)250 (- 3 2)251 (+ 3 2)) ===> 1252253==== Assignments254255<macro>(set! <variable> <expression>)</macro><br>256257<Expression> is evaluated, and the resulting value is stored in the258location to which <variable> is bound. <Variable> must be bound either259in some region enclosing the set! expression or at top level. The260result of the set! expression is unspecified.261262 (define x 2)263 (+ x 1) ===> 3264 (set! x 4) ===> unspecified265 (+ x 1) ===> 5266267As an extension to R7RS, {{set!}} for unbound toplevel variables is268allowed. Also, {{(set! (PROCEDURE ...) ...)}} is supported, as CHICKEN269implements [[http://srfi.schemers.org/srfi-17/srfi-17.html|SRFI-17]].270271==== Inclusion272273<macro>(include STRING1 STRING2 ...)</macro>274<macro>(include-ci STRING1 STRING2 ...)</macro>275276Semantics: Both {{include}} and {{include-ci}} take one or277more filenames expressed as string literals, find the corresponding278files, read the contents of the files in the specified order279as if by repeated applications of {{read}}, and effectively replace the {{include}}280or {{include-ci}} expression with a {{begin}}281expression containing what was read from the files. The282difference between the two is that {{include-ci}} reads each283file as if it began with the {{#!fold-case}} directive, while284{{include}} does not.285286If the given filenames are relative paths, they are searched in the287directory containing the file where the {{include}} form appears,288then in the paths given in the list returned by {{include-path}}289(from the {{(chicken platform)}} module) or in the extension290repository directory.291292293=== Derived expression types294295The constructs in this section are hygienic. For reference purposes,296these macro definitions will convert most of the constructs described297in this section into the primitive constructs described in the298previous section. This does not necessarily mean that's exactly how299it's implemented in CHICKEN.300301==== Conditionals302303<macro>(cond <clause[1]> <clause[2]> ...)</macro><br>304305Syntax: Each <clause> should be of the form306307 (<test> <expression[1]> ...)308309where <test> is any expression. Alternatively, a <clause> may be of the310form311312 (<test> => <expression>)313314The last <clause> may be an "else clause," which has the form315316 (else <expression[1]> <expression[2]> ...).317318Semantics: A cond expression is evaluated by evaluating the <test>319expressions of successive <clause>s in order until one of them320evaluates to a true value (see [[#Booleans|the section about321booleans]] below). When a <test> evaluates to a true value, then the322remaining <expression>s in its <clause> are evaluated in order, and323the result(s) of the last <expression> in the <clause> is(are)324returned as the result(s) of the entire cond expression. If the325selected <clause> contains only the <test> and no <expression>s, then326the value of the <test> is returned as the result. If the selected327<clause> uses the => alternate form, then the <expression> is328evaluated. Its value must be a procedure that accepts one argument;329this procedure is then called on the value of the <test> and the330value(s) returned by this procedure is(are) returned by the cond331expression. If all <test>s evaluate to false values, and there is no332else clause, then the result of the conditional expression is333unspecified; if there is an else clause, then its <expression>s are334evaluated, and the value(s) of the last one is(are) returned.335336 (cond ((> 3 2) 'greater)337 ((< 3 2) 'less)) ===> greater338 (cond ((> 3 3) 'greater)339 ((< 3 3) 'less)340 (else 'equal)) ===> equal341 (cond ((assv 'b '((a 1) (b 2))) => cadr)342 (else #f)) ===> 2343344345As an extension to R7RS, CHICKEN also supports the346[[http://srfi.schemers.org/srfi-61|SRFI-61]] syntax:347348 (<generator> <guard> => <expression>)349350In this situation, {{generator}} is ''always'' evaluated. Its351resulting value(s) are used as argument(s) for the {{guard}}352procedure. Finally, if {{guard}} returns a non-{{#f}} value, the353{{expression}} is evaluated by calling it with the result of354{{guard}}. Otherwise, evaluation procedes to the next clause.355356<macro>(case <key> <clause[1]> <clause[2]> ...)</macro><br>357358Syntax: <Key> may be any expression. Each <clause> should have the form359360 ((<datum[1]> ...) <expression[1]> <expression[2]> ...),361362where each <datum> is an external representation of some object.363Alternatively, as per R7RS, a <clause> may be of the form364365 ((<datum[1]> ...) => <expression>).366367All the <datum>s must be distinct. The last <clause> may be an368"else clause," which has one of the following two forms:369370 (else <expression[1]> <expression[2]> ...)371 (else => <expression>).372373Semantics: A case expression is evaluated as follows. <Key> is374evaluated and its result is compared against each <datum>. If the375result of evaluating <key> is equivalent (in the sense of {{eqv?}};376see [[#equivalence-predicates|below]]) to a <datum>, then the377expressions in the corresponding <clause> are evaluated from left to378right and the result(s) of the last expression in the <clause> is(are)379returned as the result(s) of the case expression. If the selected380<clause> uses the => alternate form (an R7RS extension), then the381<expression> is evaluated. Its value must be a procedure that accepts382one argument; this procedure is then called on the value of the <key>383and the value(s) returned by this procedure is(are) returned by the384case expression. If the result of evaluating <key> is different from385every <datum>, then if there is an else clause its expressions are386evaluated and the result(s) of the last is(are) the result(s) of the387case expression; otherwise the result of the case expression is388unspecified.389390 (case (* 2 3)391 ((2 3 5 7) 'prime)392 ((1 4 6 8 9) 'composite)) ===> composite393 (case (car '(c d))394 ((a) 'a)395 ((b) 'b)) ===> unspecified396 (case (car '(c d))397 ((a e i o u) 'vowel)398 ((w y) 'semivowel)399 (else 'consonant)) ===> consonant400401<macro>(and <test[1]> ...)</macro><br>402403The <test> expressions are evaluated from left to right, and the value404of the first expression that evaluates to a false value (see405[[#Booleans|the section about booleans]]) is returned. Any remaining406expressions are not evaluated. If all the expressions evaluate to true407values, the value of the last expression is returned. If there are no408expressions then #t is returned.409410 (and (= 2 2) (> 2 1)) ===> #t411 (and (= 2 2) (< 2 1)) ===> #f412 (and 1 2 'c '(f g)) ===> (f g)413 (and) ===> #t414415<macro>(or <test[1]> ...)</macro><br>416417The <test> expressions are evaluated from left to right, and the value418of the first expression that evaluates to a true value (see419[[#Booleans|the section about booleans]]) is returned. Any remaining420expressions are not evaluated. If all expressions evaluate to false421values, the value of the last expression is returned. If there are no422expressions then #f is returned.423424 (or (= 2 2) (> 2 1)) ===> #t425 (or (= 2 2) (< 2 1)) ===> #t426 (or #f #f #f) ===> #f427 (or (memq 'b '(a b c))428 (/ 3 0)) ===> (b c)429430<macro>(unless TEST EXP1 EXP2 ...)</macro>431432Equivalent to:433434<enscript highlight=scheme>435(if (not TEST) (begin EXP1 EXP2 ...))436</enscript>437438<macro>(when TEST EXP1 EXP2 ...)</macro>439440Equivalent to:441442<enscript highlight=scheme>443(if TEST (begin EXP1 EXP2 ...))444</enscript>445446<macro>(cond-expand <ce-clause1> <ce-clause2> ...)</macro>447448The {{cond-expand}} expression type provides a way449to statically expand different expressions depending on the450implementation. A <ce-clause> takes the following form:451452{{453(<feature requirement> <expression> ...)454}}455456The last clause can be an "else clause," which has the form457458{{459(else <expression> ...)460}}]461462A feature requirement takes one of the following forms:463464<feature identifier>465466{{(library <library name>)}}467468{{(and <feature requirement> ...)}}469470{{(or <feature requirement> ...)}}471472{{(not <feature requirement>)}}473474Each implementation maintains a list of475feature identifiers which are present, as well as a list476of libraries which can be imported.477The value of a <feature requirement> is determined by replacing each478<feature identifier> and {{(library <library name>)}} on the479implementation's lists with {{#t}}, and all other feature identifiers and library names with {{#f}}, then evaluating the resulting expression as a Scheme boolean expression under480the normal interpretation of {{and}}, {{or}}, and {{not}}.481482A {{cond-expand}} is then expanded by evaluating the483<feature requirement>s of successive <ce-clause>s in order484until one of them returns {{#t}}. When a true clause is found,485the corresponding <expression>s are expanded to a {{begin}},486and the remaining clauses are ignored.487488If none of the489<feature requirement>s evaluate to {{#t}}, then if there is an490{{else}} clause, its <expression>s are included. Otherwise, the491behavior of the {{cond}}-expand is unspecified. Unlike {{cond}},492{{cond-expand}} does not depend on the value of any variables.493494The following features are built-in and always available by default:495{{chicken}}, {{srfi-0}}, {{srfi-2}}, {{srfi-6}}, {{srfi-8}}, {{srfi-9}},496{{srfi-11}}, {{srfi-12}}, {{srfi-15}}, {{srfi-16}}, {{srfi-17}}, {{srfi-23}},497{{srfi-26}}, {{srfi-28}}, {{srfi-30}}, {{srfi-31}}, {{srfi-39}}, {{srfi-46}},498{{srfi-55}}, {{srfi-61}}, {{srfi-62}}, {{srfi-87}}, {{srfi-88}}.499500There are also situation-specific feature identifiers: {{compiling}} during501compilation, {{csi}} when running in the interpreter, and {{compiler-extension}}502when running within the compiler.503504The symbols returned by the following procedures from505[[Module (chicken platform)|(chicken platform)]] are also available506as feature-identifiers in all situations: {{(machine-byte-order)}},507{{(machine-type)}}, {{(software-type)}}, {{(software-version)}}. For508example, the {{machine-type}} class of feature-identifiers include509{{arm}}, {{alpha}}, {{mips}}, etc.510511Platform endianness is indicated by the {{little-endian}} and {{big-endian}}512features.513514In addition the following feature-identifiers may exist: {{cross-chicken}},515{{dload}}, {{gchooks}}, {{ptables}}, {{case-insensitive}}.516517518==== Binding constructs519520The three binding constructs let, let*, and letrec give Scheme a block521structure, like Algol 60. The syntax of the three constructs is522identical, but they differ in the regions they establish for their523variable bindings. In a let expression, the initial values are computed524before any of the variables become bound; in a let* expression, the525bindings and evaluations are performed sequentially; while in a letrec526expression, all the bindings are in effect while their initial values527are being computed, thus allowing mutually recursive definitions.528529<macro>(let <bindings> <body>)</macro><br>530531Syntax: <Bindings> should have the form532533 ((<variable[1]> <init[1]>) ...),534535where each <init> is an expression, and <body> should be a sequence of536one or more expressions. It is an error for a <variable> to appear more537than once in the list of variables being bound.538539Semantics: The <init>s are evaluated in the current environment (in540some unspecified order), the <variable>s are bound to fresh locations541holding the results, the <body> is evaluated in the extended542environment, and the value(s) of the last expression of <body> is(are)543returned. Each binding of a <variable> has <body> as its region.544545 (let ((x 2) (y 3))546 (* x y)) ===> 6547548 (let ((x 2) (y 3))549 (let ((x 7)550 (z (+ x y)))551 (* z x))) ===> 35552553See also "named let", [[#iteration|below]].554555<macro>(let* <bindings> <body>)</macro><br>556557Syntax: <Bindings> should have the form558559 ((<variable[1]> <init[1]>) ...),560561and <body> should be a sequence of one or more expressions.562563Semantics: Let* is similar to let, but the bindings are performed564sequentially from left to right, and the region of a binding indicated565by (<variable> <init>) is that part of the let* expression to the right566of the binding. Thus the second binding is done in an environment in567which the first binding is visible, and so on.568569 (let ((x 2) (y 3))570 (let* ((x 7)571 (z (+ x y)))572 (* z x))) ===> 70573574<macro>(letrec <bindings> <body>)</macro><br>575576Syntax: <Bindings> should have the form577578 ((<variable[1]> <init[1]>) ...),579580and <body> should be a sequence of one or more expressions. It is an581error for a <variable> to appear more than once in the list of582variables being bound.583584Semantics: The <variable>s are bound to fresh locations holding585undefined values, the <init>s are evaluated in the resulting586environment (in some unspecified order), each <variable> is assigned to587the result of the corresponding <init>, the <body> is evaluated in the588resulting environment, and the value(s) of the last expression in589<body> is(are) returned. Each binding of a <variable> has the entire590letrec expression as its region, making it possible to define mutually591recursive procedures.592593 (letrec ((even?594 (lambda (n)595 (if (zero? n)596 #t597 (odd? (- n 1)))))598 (odd?599 (lambda (n)600 (if (zero? n)601 #f602 (even? (- n 1))))))603 (even? 88))604 ===> #t605606One restriction on letrec is very important: it must be possible to607evaluate each <init> without assigning or referring to the value of any608<variable>. If this restriction is violated, then it is an error. The609restriction is necessary because Scheme passes arguments by value610rather than by name. In the most common uses of letrec, all the <init>s611are lambda expressions and the restriction is satisfied automatically.612613<macro>(letrec* <bindings> <body>) </macro>614615Syntax: <Bindings> has the form {{((<variable[1]> <init[1]>) ...)}}, and616<body> is a sequence of zero or more617definitions followed by one or more expressions as described in section 4.1.4.618It is an error for a <variable> to appear more than once in the list of619variables being bound.620621Semantics: The <variable>s are bound to fresh locations, each <variable> is622assigned in left-to-right order to the result of evaluating the corresponding623<init> (interleaving evaluations and assignments), the <body> is evaluated in624the resulting environment, and the values of the last expression in <body> are625returned. Despite the left-to-right evaluation and assignment order, each626binding of a <variable> has the entire letrec* expression as its region, making627it possible to define mutually recursive procedures.628629If it is not possible to evaluate each <init> without assigning or referring to630the value of the corresponding <variable> or the <variable> of any of the631bindings that follow it in <bindings>, it is an error. Another restriction is632that it is an error to invoke the continuation of an <init> more than once.633634 ;; Returns the arithmetic, geometric, and635 ;; harmonic means of a nested list of numbers636 (define (means ton)637 (letrec*638 ((mean639 (lambda (f g)640 (f (/ (sum g ton) n))))641 (sum642 (lambda (g ton)643 (if (null? ton)644 (+)645 (if (number? ton)646 (g ton)647 (+ (sum g (car ton))648 (sum g (cdr ton)))))))649 (n (sum (lambda (x) 1) ton)))650 (values (mean values values)651 (mean exp log)652 (mean / /))))653654Evaluating {{(means '(3 (1 4)))}} returns three values: 8/3, 2.28942848510666655(approximately), and 36/19.656657<macro>(let-values <mv binding spec> <body>)</macro>658659Syntax: <Mv binding spec> has the form {{((<formals[1]> <init[1]>) ...)}},660where each <init> is an expression, and <body> is661zero or more definitions followed by a sequence of one or more expressions as662described in section 4.1.4. It is an error for a variable to appear more than663once in the set of <formals>.664665Semantics: The <init>s are evaluated in the current environment (in some666unspecified order) as if by invoking call-with-values, and the variables667occurring in the <formals> are bound to fresh locations holding the values668returned by the <init>s, where the <formals> are matched to the return values669in the same way that the <formals> in a lambda expression are matched to the670arguments in a procedure call. Then, the <body> is evaluated in the extended671environment, and the values of the last expression of <body> are returned. Each672binding of a <variable> has <body> as its region.673674It is an error if the <formals> do not match the number of values returned by675the corresponding <init>.676677 (let-values (((root rem) (exact-integer-sqrt 32)))678 (* root rem)) ==> 35679680<macro>(let*-values <mv binding spec> <body>)</macro>681682Syntax: <Mv binding spec> has the form {{((<formals> <init>) ...)}},683and <body> is a sequence of zero or more definitions684followed by one or more expressions as described in section 4.1.4. In each685<formals>, it is an error if any variable appears more than once.686687Semantics: The let*-values construct is similar to let-values, but the <init>s688are evaluated and bindings created sequentially from left to right, with the689region of the bindings of each <formals> including the <init>s to its right as690well as <body>. Thus the second <init> is evaluated in an environment in which691the first set of bindings is visible and initialized, and so on.692693 (let ((a 'a) (b 'b) (x 'x) (y 'y))694 (let*-values (((a b) (values x y))695 ((x y) (values a b)))696 (list a b x y))) ===> (x y x y)697698==== Sequencing699700<macro>(begin <expression[1]> <expression[2]> ...)</macro><br>701702The <expression>s are evaluated sequentially from left to right, and703the value(s) of the last <expression> is(are) returned. This expression704type is used to sequence side effects such as input and output.705706 (define x 0)707708 (begin (set! x 5)709 (+ x 1)) ===> 6710711 (begin (display "4 plus 1 equals ")712 (display (+ 4 1))) ===> unspecified713 and prints 4 plus 1 equals 5714715As an extension to R7RS, CHICKEN also allows {{(begin)}} without body716expressions in any context, not just at toplevel. This simply717evaluates to the unspecified value.718719720==== Iteration721722<macro>(do ((<variable[1]> <init[1]> <step[1]>) ...) (<test> <expression> ...) <command> ...)</macro><br>723724Do is an iteration construct. It specifies a set of variables to be725bound, how they are to be initialized at the start, and how they are to726be updated on each iteration. When a termination condition is met, the727loop exits after evaluating the <expression>s.728729Do expressions are evaluated as follows: The <init> expressions are730evaluated (in some unspecified order), the <variable>s are bound to731fresh locations, the results of the <init> expressions are stored in732the bindings of the <variable>s, and then the iteration phase begins.733734Each iteration begins by evaluating <test>; if the result is false735(see [[#Booleans|the section about booleans]]), then the <command>736expressions are evaluated in order for effect, the <step> expressions737are evaluated in some unspecified order, the <variable>s are bound to738fresh locations, the results of the <step>s are stored in the bindings739of the <variable>s, and the next iteration begins.740741If <test> evaluates to a true value, then the <expression>s are742evaluated from left to right and the value(s) of the last <expression>743is(are) returned. If no <expression>s are present, then the value of744the do expression is unspecified.745746The region of the binding of a <variable> consists of the entire do747expression except for the <init>s. It is an error for a <variable> to748appear more than once in the list of do variables.749750A <step> may be omitted, in which case the effect is the same as if751(<variable> <init> <variable>) had been written instead of (<variable>752<init>).753754 (do ((vec (make-vector 5))755 (i 0 (+ i 1)))756 ((= i 5) vec)757 (vector-set! vec i i)) ===> #(0 1 2 3 4)758759 (let ((x '(1 3 5 7 9)))760 (do ((x x (cdr x))761 (sum 0 (+ sum (car x))))762 ((null? x) sum))) ===> 25763764<macro>(let <variable> <bindings> <body>)</macro><br>765766"Named let" is a variant on the syntax of let which provides a more767general looping construct than do and may also be used to express768recursions. It has the same syntax and semantics as ordinary let except769that <variable> is bound within <body> to a procedure whose formal770arguments are the bound variables and whose body is <body>. Thus the771execution of <body> may be repeated by invoking the procedure named by772<variable>.773774 (let loop ((numbers '(3 -2 1 6 -5))775 (nonneg '())776 (neg '()))777 (cond ((null? numbers) (list nonneg neg))778 ((>= (car numbers) 0)779 (loop (cdr numbers)780 (cons (car numbers) nonneg)781 neg))782 ((< (car numbers) 0)783 (loop (cdr numbers)784 nonneg785 (cons (car numbers) neg)))))786 ===> ((6 1 3) (-5 -2))787788==== Dynamic bindings789790The dynamic extent of a procedure call is the time between when it is initiated791and when it returns. In Scheme, {{call-with-current-continuation}}792allows reentering a dynamic extent after its procedure call has returned. Thus,793the dynamic extent of a call might not be a single, continuous time period.794795This sections introduces parameter objects, which can be bound to new values796for the duration of a dynamic extent. The set of all parameter bindings at a797given time is called the dynamic environment.798799<procedure>(make-parameter init [converter])</procedure>800801Returns a newly allocated parameter object, which is a procedure that accepts802zero arguments and returns the value associated with the parameter object.803Initially, this value is the value of {{(converter init)}}, or of {{init}}804if the conversion procedure {{converter}} is not specified. The associated value can be temporarily changed805using {{parameterize}}, which is described below.806807The effect of passing arguments to a parameter object is808implementation-dependent.809810<syntax>(parameterize ((<param[1]> <value[1]>) ...) <body>)</syntax>811812Syntax: Both <param[1]> and <value[1]> are expressions.813814It is an error if the value of any <param> expression is not a parameter815object.816817Semantics: A parameterize expression is used to change the values returned by818specified parameter objects during the evaluation of the body.819820The <param> and <value> expressions are evaluated in an unspecified order. The821<body> is evaluated in a dynamic environment in which calls to the parameters822return the results of passing the corresponding values to the conversion823procedure specified when the parameters were created. Then the previous values824of the parameters are restored without passing them to the conversion825procedure. The results of the last expression in the <body> are returned as the826results of the entire parameterize expression.827828Note: If the conversion procedure is not idempotent, the results of829(parameterize ((x (x))) ...), which appears to bind the parameter830831x to its current value, might not be what the user expects.832833If an implementation supports multiple threads of execution, then parameterize834must not change the associated values of any parameters in any thread other835than the current thread and threads created inside <body>.836837Parameter objects can be used to specify configurable settings for a838computation without the need to pass the value to every procedure in the call839chain explicitly.840841 (define radix842 (make-parameter843 10844 (lambda (x)845 (if (and (exact-integer? x) (<= 2 x 16))846 x847 (error "invalid radix")))))848849 (define (f n) (number->string n (radix)))850851 (f 12) ==> "12"852 (parameterize ((radix 2))853 (f 12)) ==> "1100"854 (f 12) ==> "12"855856 (radix 16) ==> unspecified857858 (parameterize ((radix 0))859 (f 12)) ==> error860861==== Exception handling862863<macro>(guard (<variable> <cond clause[1]> <cond clause[2]> ...) <body>)</macro>864865Syntax: Each <cond clause> is as in the specification of cond.866867Semantics: The <body> is evaluated with an exception handler that binds the868raised object (see {{raise}}) to <variable> and, within the scope869of that binding, evaluates the clauses as if they were the clauses of a cond870expression. That implicit cond expression is evaluated with the continuation871and dynamic environment of the guard expression. If every <cond clause>'s872<test> evaluates to #f and there is no else clause, then raise-continuable is873invoked on the raised object within the dynamic environment of the original874call to raise or raise-continuable, except that the current exception handler875is that of the guard expression.876877 (guard (condition878 ((assq 'a condition) => cdr)879 ((assq 'b condition)))880 (raise (list (cons 'a 42))))881 ==> 42882883 (guard (condition884 ((assq 'a condition) => cdr)885 ((assq 'b condition)))886 (raise (list (cons 'b 23))))887 ==> (b . 23)888889==== Quasiquotation890891<macro>(quasiquote <qq template>)</macro><br>892<macro>`<qq template></macro><br>893894"Backquote" or "quasiquote" expressions are useful for constructing895a list or vector structure when most but not all of the desired896structure is known in advance. If no commas appear within the <qq897template>, the result of evaluating `<qq template> is equivalent to the898result of evaluating '<qq template>. If a comma appears within the <qq899template>, however, the expression following the comma is evaluated900("unquoted") and its result is inserted into the structure instead of901the comma and the expression. If a comma appears followed immediately902by an at-sign (@), then the following expression must evaluate to a903list; the opening and closing parentheses of the list are then904"stripped away" and the elements of the list are inserted in place of905the comma at-sign expression sequence. A comma at-sign should only906appear within a list or vector <qq template>.907908 `(list ,(+ 1 2) 4) ===> (list 3 4)909 (let ((name 'a)) `(list ,name ',name))910 ===> (list a (quote a))911 `(a ,(+ 1 2) ,@(map abs '(4 -5 6)) b)912 ===> (a 3 4 5 6 b)913 `(( foo ,(- 10 3)) ,@(cdr '(c)) . ,(car '(cons)))914 ===> ((foo 7) . cons)915 `#(10 5 ,(sqrt 4) ,@(map sqrt '(16 9)) 8)916 ===> #(10 5 2 4 3 8)917918Quasiquote forms may be nested. Substitutions are made only for919unquoted components appearing at the same nesting level as the920outermost backquote. The nesting level increases by one inside each921successive quasiquotation, and decreases by one inside each922unquotation.923924 `(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f)925 ===> (a `(b ,(+ 1 2) ,(foo 4 d) e) f)926 (let ((name1 'x)927 (name2 'y))928 `(a `(b ,,name1 ,',name2 d) e))929 ===> (a `(b ,x ,'y d) e)930931The two notations `<qq template> and (quasiquote <qq template>) are932identical in all respects. ,<expression> is identical to (unquote933<expression>), and ,@<expression> is identical to (unquote-splicing934<expression>). The external syntax generated by write for two-element935lists whose car is one of these symbols may vary between936implementations.937938 (quasiquote (list (unquote (+ 1 2)) 4))939 ===> (list 3 4)940 '(quasiquote (list (unquote (+ 1 2)) 4))941 ===> `(list ,(+ 1 2) 4)942 i.e., (quasiquote (list (unquote (+ 1 2)) 4))943944Unpredictable behavior can result if any of the symbols quasiquote,945unquote, or unquote-splicing appear in positions within a <qq template>946otherwise than as described above.947948=== Macros949950Scheme programs can define and use new derived expression types, called951macros. Program-defined expression types have the syntax952953 (<keyword> <datum> ...)954955where <keyword> is an identifier that uniquely determines the956expression type. This identifier is called the syntactic keyword, or957simply keyword, of the macro. The number of the <datum>s, and their958syntax, depends on the expression type.959960Each instance of a macro is called a use of the macro. The set of rules961that specifies how a use of a macro is transcribed into a more962primitive expression is called the transformer of the macro.963964The macro definition facility consists of two parts:965966* A set of expressions used to establish that certain identifiers are967 macro keywords, associate them with macro transformers, and control968 the scope within which a macro is defined, and969970* a pattern language for specifying macro transformers.971972The syntactic keyword of a macro may shadow variable bindings, and973local variable bindings may shadow keyword bindings. All macros defined974using the pattern language are "hygienic" and "referentially975transparent" and thus preserve Scheme's lexical scoping:976977* If a macro transformer inserts a binding for an identifier978 (variable or keyword), the identifier will in effect be renamed979 throughout its scope to avoid conflicts with other identifiers.980 Note that a define at top level may or may not introduce a binding;981 this depends on whether the binding already existed before (in which982 case its value will be overridden).983984* If a macro transformer inserts a free reference to an identifier,985 the reference refers to the binding that was visible where the986 transformer was specified, regardless of any local bindings that987 may surround the use of the macro.988989==== Binding constructs for syntactic keywords990991Let-syntax and letrec-syntax are analogous to let and letrec, but they992bind syntactic keywords to macro transformers instead of binding993variables to locations that contain values. Syntactic keywords may also994be bound at top level.995996<macro>(let-syntax <bindings> <body>)</macro><br>997998Syntax: <Bindings> should have the form9991000 ((<keyword> <transformer spec>) ...)10011002Each <keyword> is an identifier, each <transformer spec> is an instance1003of syntax-rules, and <body> should be a sequence of one or more1004expressions. It is an error for a <keyword> to appear more than once in1005the list of keywords being bound.10061007Semantics: The <body> is expanded in the syntactic environment obtained1008by extending the syntactic environment of the let-syntax expression1009with macros whose keywords are the <keyword>s, bound to the specified1010transformers. Each binding of a <keyword> has <body> as its region.10111012 (let-syntax ((when (syntax-rules ()1013 ((when test stmt1 stmt2 ...)1014 (if test1015 (begin stmt11016 stmt2 ...))))))1017 (let ((if #t))1018 (when if (set! if 'now))1019 if)) ===> now10201021 (let ((x 'outer))1022 (let-syntax ((m (syntax-rules () ((m) x))))1023 (let ((x 'inner))1024 (m)))) ===> outer10251026<macro>(letrec-syntax <bindings> <body>)</macro><br>10271028Syntax: Same as for let-syntax.10291030Semantics: The <body> is expanded in the syntactic environment obtained1031by extending the syntactic environment of the letrec-syntax expression1032with macros whose keywords are the <keyword>s, bound to the specified1033transformers. Each binding of a <keyword> has the <bindings> as well as1034the <body> within its region, so the transformers can transcribe1035expressions into uses of the macros introduced by the letrec-syntax1036expression.10371038 (letrec-syntax1039 ((my-or (syntax-rules ()1040 ((my-or) #f)1041 ((my-or e) e)1042 ((my-or e1 e2 ...)1043 (let ((temp e1))1044 (if temp1045 temp1046 (my-or e2 ...)))))))1047 (let ((x #f)1048 (y 7)1049 (temp 8)1050 (let odd?)1051 (if even?))1052 (my-or x1053 (let temp)1054 (if y)1055 y))) ===> 710561057==== Pattern language10581059A <transformer spec> has the following form:10601061 (syntax-rules <literals> <syntax rule> ...)10621063Syntax: <Literals> is a list of identifiers and each <syntax rule>1064should be of the form10651066 (<pattern> <template>)10671068The <pattern> in a <syntax rule> is a list <pattern> that begins with1069the keyword for the macro.10701071A <pattern> is either an identifier, a constant, or one of the1072following10731074 (<pattern> ...)1075 (<pattern> <pattern> ... . <pattern>)1076 (<pattern> ... <pattern> <ellipsis> <pattern> ...)1077 #(<pattern> ...)1078 #(<pattern> ... <pattern> <ellipsis>)10791080and a template is either an identifier, a constant, or one of the1081following10821083 (<element> ...)1084 (<element> <element> ... . <template>)1085 (<ellipsis> <template>)1086 #(<element> ...)10871088where an <element> is a <template> optionally followed by an <ellipsis>1089and an <ellipsis> is the identifier "...".10901091Semantics: An instance of syntax-rules produces a new macro transformer1092by specifying a sequence of hygienic rewrite rules. A use of a macro1093whose keyword is associated with a transformer specified by1094syntax-rules is matched against the patterns contained in the <syntax1095rule>s, beginning with the leftmost <syntax rule>. When a match is1096found, the macro use is transcribed hygienically according to the1097template.10981099An identifier appearing within a <pattern> can be an underscore ({{_}}), a literal1100identifier listed in the list of <pattern literal>s, or the <ellipsis>. All1101other identifiers appearing within a <pattern> are pattern variables.11021103The keyword at the beginning of the pattern in a <syntax rule> is not involved1104in the matching and is considered neither a pattern variable nor a literal1105identifier.11061107Pattern variables match arbitrary input elements and are used to refer to1108elements of the input in the template. It is an error for the same pattern1109variable to appear more than once in a <pattern>.11101111Underscores also match arbitrary input elements but are not pattern variables1112and so cannot be used to refer to those elements. If an underscore appears in1113the <pattern literal>s list, then that takes precedence and underscores in the1114<pattern> match as literals. Multiple underscores can appear in a <pattern>.11151116Identifiers that appear in (<pattern literal> ...) are interpreted as literal1117identifiers to be matched against corresponding elements of the input. An1118element in the input matches a literal identifier if and only if it is an1119identifier and either both its occurrence in the macro expression and its1120occurrence in the macro definition have the same lexical binding, or the two1121identifiers are the same and both have no lexical binding.11221123A subpattern followed by <ellipsis> can match zero or more elements of the1124input, unless <ellipsis> appears in the <pattern literal>s, in which case it is1125matched as a literal.11261127More formally, an input form F matches a pattern P if and only if:11281129* P is an underscore (_).11301131* P is a non-literal identifier; or11321133* P is a literal identifier and F is an identifier with the same1134 binding; or11351136* P is a list (P[1] ... P[n]) and F is a list of n forms that match P1137 [1] through P[n], respectively; or11381139* P is an improper list (P[1] P[2] ... P[n] . P[n+1]) and F is a list1140 or improper list of n or more forms that match P[1] through P[n],1141 respectively, and whose nth "cdr" matches P[n+1]; or11421143* P is of the form (P[1] ... P[k] P[e] <ellipsis> P[m+1] ... P[n] . P[x]) where E1144 is a list or improper list of n elements, the first k of which match P[1]1145 through P[k], whose next m--k elements each match P[e], whose remaining n--m1146 elements match P[m+1] through P[n], and whose nth and final cdr matches P[x1147 ]; or11481149* P is a vector of the form #(P[1] ... P[n]) and F is a vector of n1150 forms that match P[1] through P[n]; or11511152* P is of the form #(P[1] ... P[k] P[e] <ellipsis> P[m+1] ... P[n]) where E is a1153 vector of n elements the first k of which match P[1] through P[k], whose1154 next m--k elements each match P[e], and whose remaining n--m elements match P1155 [m+1] through P[n]; or11561157* P is a datum and F is equal to P in the sense of the equal?1158 procedure.11591160It is an error to use a macro keyword, within the scope of its binding,1161in an expression that does not match any of the patterns.11621163When a macro use is transcribed according to the template of the matching1164<syntax rule>, pattern variables that occur in the template are replaced by the1165elements they match in the input. Pattern variables that occur in subpatterns1166followed by one or more instances of the identifier <ellipsis> are allowed only1167in subtemplates that are followed by as many instances of <ellipsis>. They are1168replaced in the output by all of the elements they match in the input,1169distributed as indicated. It is an error if the output cannot be built up as1170specified.11711172Identifiers that appear in the template but are not pattern variables or the1173identifier <ellipsis> are inserted into the output as literal identifiers. If a1174literal identifier is inserted as a free identifier then it refers to the1175binding of that identifier within whose scope the instance of syntax-rules1176appears. If a literal identifier is inserted as a bound identifier then it is1177in effect renamed to prevent inadvertent captures of free identifiers.11781179A template of the form (<ellipsis> <template>) is identical to <template>,1180except that ellipses within the template have no special meaning. That is, any1181ellipses contained within <template> are treated as ordinary identifiers. In1182particular, the template (<ellipsis> <ellipsis>) produces a single <ellipsis>.1183This allows syntactic abstractions to expand into code containing ellipses.11841185{{1186(define-syntax be-like-begin1187 (syntax-rules ()1188 ((be-like-begin name)1189 (define-syntax name1190 (syntax-rules ()1191 ((name expr (... ...))1192 (begin expr (... ...))))))))11931194(be-like-begin sequence)11951196(sequence 1 2 3 4) ==> 41197}}11981199As an example, if {{let}} and {{cond}} have their standard meaning1200then they are hygienic (as required) and the following is not an1201error.12021203 (let ((=> #f))1204 (cond (#t => 'ok))) ===> ok12051206The macro transformer for cond recognizes => as a local variable, and1207hence an expression, and not as the top-level identifier =>, which the1208macro transformer treats as a syntactic keyword. Thus the example1209expands into12101211 (let ((=> #f))1212 (if #t (begin => 'ok)))12131214instead of12151216 (let ((=> #f))1217 (let ((temp #t))1218 (if temp ('ok temp))))12191220which would result in an invalid procedure call.12211222==== Signaling errors in macro transformers12231224<macro>(syntax-error <message> <args> ...)</macro>12251226{{syntax-error}} behaves similarly to {{error}} except that implementations with1227an expansion pass separate from evaluation should signal an error as soon as1228{{syntax-error}} is expanded. This can be used as a syntax-rules <template> for a1229<pattern> that is an invalid use of the macro, which can provide more1230descriptive error messages. <message> is a string literal, and <args> arbitrary1231expressions providing additional information. Applications cannot count on1232being able to catch syntax errors with exception handlers or guards.12331234 (define-syntax simple-let1235 (syntax-rules ()1236 ((_ (head ... ((x . y) val) . tail)1237 body1 body2 ...)1238 (syntax-error1239 "expected an identifier but got"1240 (x . y)))1241 ((_ ((name val) ...) body1 body2 ...)1242 ((lambda (name ...) body1 body2 ...)1243 val ...))))124412451246== Program structure12471248=== Programs12491250A Scheme program consists of a sequence of expressions, definitions,1251and syntax definitions. Expressions are described in chapter 4;1252definitions and syntax definitions are the subject of the rest of the1253present chapter.12541255Programs are typically stored in files or entered interactively to a1256running Scheme system, although other paradigms are possible;1257questions of user interface lie outside the scope of this1258report. (Indeed, Scheme would still be useful as a notation for1259expressing computational methods even in the absence of a mechanical1260implementation.)12611262Definitions and syntax definitions occurring at the top level of a1263program can be interpreted declaratively. They cause bindings to be1264created in the top level environment or modify the value of existing1265top-level bindings. Expressions occurring at the top level of a1266program are interpreted imperatively; they are executed in order when1267the program is invoked or loaded, and typically perform some kind of1268initialization.12691270At the top level of a program (begin <form1> ...) is equivalent to the1271sequence of expressions, definitions, and syntax definitions that form1272the body of the begin.12731274=== Import declarations12751276<macro>(import IMPORT-SET ...)</macro>12771278An import declaration provides a way to import identifiers exported by a1279library. Each <import set> names a set of bindings from a library and possibly1280specifies local names for the imported bindings. It takes one of the following1281forms:12821283* <library name>12841285* {{(only <import set> <identifier> ...)}}12861287* {{(except <import set> <identifier> ...)}}12881289* {{(prefix <import set> <identifier>)}}12901291* {{(rename <import set> (<identifier[1]> <identifier[2]>) ...)}}12921293In the first form, all of the identifiers in the named library's export clauses1294are imported with the same names (or the exported names if exported with rename1295). The additional <import set> forms modify this set as follows:12961297* only produces a subset of the given <import set> including only the listed1298 identifiers (after any renaming). It is an error if any of the listed1299 identifiers are not found in the original set.13001301* except produces a subset of the given <import set>, excluding the listed1302 identifiers (after any renaming). It is an error if any of the listed1303 identifiers are not found in the original set.13041305* rename modifies the given <import set>, replacing each instance of1306 <identifier[1]> with <identifier[2]>. It is an error if any of the listed1307 <identifier[1]>s are not found in the original set.13081309* prefix automatically renames all identifiers in the given <import set>,1310 prefixing each with the specified <identifier>.13111312=== Definitions13131314Definitions are valid in some, but not all, contexts where expressions1315are allowed. They are valid only at the top level of a <program> and1316at the beginning of a <body>.13171318A definition should have one of the following forms:13191320<macro>(define <variable> <expression>)</macro><br>1321<macro>(define (<variable> <formals>) <body>)</macro><br>13221323<Formals> should be either a sequence of zero or more variables, or a1324sequence of one or more variables followed by a space-delimited period1325and another variable (as in a lambda expression). This form is1326equivalent to13271328 (define <variable>1329 (lambda (<formals>) <body>)).13301331<macro>(define <variable>)</macro>13321333This form is a CHICKEN extension to R7RS, and is equivalent to13341335 (define <variable> (void))13361337<macro>(define (<variable> . <formal>) <body>)</macro><br>13381339<Formal> should be a single variable. This form is equivalent to13401341 (define <variable>1342 (lambda <formal> <body>)).13431344<macro>(define ((<variable> <formal> ...) ...) <body>)</macro><br>13451346As an extension to R7RS, CHICKEN allows ''curried'' definitions, where1347the variable name may also be a list specifying a name and a nested1348lambda list. For example,13491350 (define ((make-adder x) y) (+ x y))13511352is equivalent to13531354 (define (make-adder x) (lambda (y) (+ x y))).13551356This type of curried definition can be nested arbitrarily and combined1357with dotted tail notation or DSSSL keywords.13581359==== Top level definitions13601361At the top level of a program, a definition13621363 (define <variable> <expression>)13641365has essentially the same effect as the assignment expression13661367 (set! <variable> <expression>)13681369if <variable> is bound. If <variable> is not bound, however, then the1370definition will bind <variable> to a new location before performing1371the assignment, whereas it would be an error to perform a set! on an1372unbound variable in standard Scheme. In CHICKEN, {{set!}} at toplevel1373has the same effect as a definition, unless inside a module, in which1374case it is an error.13751376 (define add31377 (lambda (x) (+ x 3)))1378 (add3 3) ===> 61379 (define first car)1380 (first '(1 2)) ===> 113811382Some implementations of Scheme use an initial environment in which all1383possible variables are bound to locations, most of which contain1384undefined values. Top level definitions in such an implementation are1385truly equivalent to assignments. In CHICKEN, attempting to evaluate1386an unbound identifier will result in an error, but you ''can'' use1387{{set!}} to bind an initial value to it.13881389==== Internal definitions13901391Definitions may occur at the beginning of a <body> (that is, the body1392of a lambda, let, let*, letrec, let-syntax, or letrec-syntax1393expression or that of a definition of an appropriate form). Such1394definitions are known as internal definitions as opposed to the top1395level definitions described above. The variable defined by an internal1396definition is local to the <body>. That is, <variable> is bound rather1397than assigned, and the region of the binding is the entire <body>. For1398example,13991400 (let ((x 5))1401 (define foo (lambda (y) (bar x y)))1402 (define bar (lambda (a b) (+ (* a b) a)))1403 (foo (+ x 3))) ===> 4514041405A <body> containing internal definitions can always be converted into1406a completely equivalent letrec expression. For example, the let1407expression in the above example is equivalent to14081409 (let ((x 5))1410 (letrec ((foo (lambda (y) (bar x y)))1411 (bar (lambda (a b) (+ (* a b) a))))1412 (foo (+ x 3))))14131414Just as for the equivalent letrec expression, it must be possible to1415evaluate each <expression> of every internal definition in a <body>1416without assigning or referring to the value of any <variable> being1417defined.14181419Wherever an internal definition may occur (begin <definition1> ...) is1420equivalent to the sequence of definitions that form the body of the1421begin.14221423CHICKEN extends the R7RS semantics by allowing internal definitions1424everywhere, and not only at the beginning of a body. A set of internal1425definitions is equivalent to a {{letrec}} form enclosing all following1426expressions in the body:14271428 (let ((foo 123))1429 (bar)1430 (define foo 456)1431 (baz foo) )14321433expands into14341435 (let ((foo 123))1436 (bar)1437 (letrec ((foo 456))1438 (baz foo) ) )14391440Local sequences of {{define-syntax}} forms are translated into1441equivalent {{letrec-syntax}} forms that enclose the following forms as1442the body of the expression.14431444=== Multiple-value definitions14451446Another kind of definition is provided by define-values, which creates multiple1447definitions from a single expression returning multiple values. It is allowed1448wherever define is allowed.14491450<macro>(define-values <formals> <expression>)</macro>14511452It is an error if a variable appears more than once in the set of <formals>.14531454Semantics: <Expression> is evaluated, and the <formals> are bound to the return1455values in the same way that the <formals> in a lambda expression are matched to1456the arguments in a procedure call.14571458 (define-values (x y) (exact-integer-sqrt 17))1459 (list x y) ==> (4 1)14601461 (let ()1462 (define-values (x y) (values 1 2))1463 (+ x y)) ==> 314641465=== Syntax definitions14661467Syntax definitions are valid only at the top level of a1468<program>. They have the following form:14691470<macro>(define-syntax <keyword> <transformer spec>)</macro>14711472{{<Keyword>}} is an identifier, and the {{<transformer spec>}} should1473be an instance of {{syntax-rules}}. Note that CHICKEN also supports1474{{er-macro-transformer}} and {{ir-macro-transformer}} here. For more1475information see [[Module (chicken syntax)|the (chicken syntax) module]].14761477The top-level syntactic environment is extended by binding the1478<keyword> to the specified transformer.14791480In standard Scheme, there is no define-syntax analogue of internal1481definitions in, but CHICKEN allows these as an extension to the1482standard. This means {{define-syntax}} may be used to define local1483macros that are visible throughout the rest of the body in which the1484definition occurred, i.e.14851486 (let ()1487 ...1488 (define-syntax foo ...)1489 (define-syntax bar ...)1490 ...)14911492is expanded into14931494 (let ()1495 ...1496 (letrec-syntax ((foo ...) (bar ...))1497 ...) )14981499{{syntax-rules}} supports [[http://srfi.schemers.org/srfi-46/|SRFI-46]]1500in allowing the ellipsis identifier to be user-defined by passing it as the first1501argument to the {{syntax-rules}} form. Also, "tail" patterns of the form15021503 (syntax-rules ()1504 ((_ (a b ... c)1505 ...15061507are supported.15081509The effect of destructively modifying the s-expression passed to a1510transformer procedure is undefined.15111512Although macros may expand into definitions and syntax definitions in1513any context that permits them, it is an error for a definition or1514syntax definition to shadow a syntactic keyword whose meaning is1515needed to determine whether some form in the group of forms that1516contains the shadowing definition is in fact a definition, or, for1517internal definitions, is needed to determine the boundary between the1518group and the expressions that follow the group. For example, the1519following are errors:15201521 (define define 3)15221523 (begin (define begin list))15241525 (let-syntax1526 ((foo (syntax-rules ()1527 ((foo (proc args ...) body ...)1528 (define proc1529 (lambda (args ...)1530 body ...))))))1531 (let ((x 3))1532 (foo (plus x y) (+ x y))1533 (define foo x)1534 (plus foo x)))15351536=== Record-type definitions15371538Record-type definitions are used to introduce new data types, called record1539types. Like other definitions, they can appear either at the outermost level or1540in a body. The values of a record type are called records and are aggregations1541of zero or more fields, each of which holds a single location. A predicate, a1542constructor, and field accessors and mutators are defined for each record type.15431544<macro>(define-record-type <name> <constructor> <pred> <field> ...)</macro>15451546Syntax: <name> and <pred> are identifiers. The <constructor> is of the form1547{{(<constructor name> <field name> ...)}} and each <field> is either of the form1548{{(<field name> <accessor name>)}} or of the form {{(<field name> <accessor name> <modifier name>)}}. It is an error for the same identifier to occur more than once1549as a field name. It is also an error for the same identifier to occur more than1550once as an accessor or mutator name.15511552The define-record-type construct is generative: each use creates a new record1553type that is distinct from all existing types, including Scheme's predefined1554types and other record types — even record types of the same name or structure.15551556An instance of define-record-type is equivalent to the following definitions:15571558* <name> is bound to a representation of the record type itself. This may be1559 a run-time object or a purely syntactic representation. The representation1560 is not utilized in this report, but it serves as a means to identify the1561 record type for use by further language extensions.15621563* <constructor name> is bound to a procedure that takes as many arguments as1564 there are <field name>s in the {{(<constructor name> ...)}} subexpression and1565 returns a new record of type <name>. Fields whose names are listed with1566 <constructor name> have the corresponding argument as their initial value.1567 The initial values of all other fields are unspecified. It is an error for1568 a field name to appear in <constructor> but not as a <field name>.15691570* <pred> is bound to a predicate that returns #t when given a value returned1571 by the procedure bound to <constructor name> and #f for everything else.15721573* Each <accessor name> is bound to a procedure that takes a record of type1574 <name> and returns the current value of the corresponding field. It is an1575 error to pass an accessor a value which is not a record of the appropriate1576 type.15771578* Each <modifier name> is bound to a procedure that takes a record of type1579 <name> and a value which becomes the new value of the corresponding field;1580 an unspecified value is returned. It is an error to pass a modifier a first1581 argument which is not a record of the appropriate type.15821583For instance, the following record-type definition15841585 (define-record-type <pare>1586 (kons x y)1587 pare?1588 (x kar set-kar!)1589 (y kdr))15901591defines kons to be a constructor, kar and kdr to be accessors, set-kar! to be a1592modifier, and pare? to be a predicate for instances of <pare>.15931594 (pare? (kons 1 2)) ===> #t1595 (pare? (cons 1 2)) ===> #f1596 (kar (kons 1 2)) ===> 11597 (kdr (kons 1 2)) ===> 21598 (let ((k (kons 1 2)))1599 (set-kar! k 3)1600 (kar k)) ===> 316011602As an extension the <modifier name> may have the form1603{{(setter PROCEDURE)}}, which will define a SRFI-17 setter-procedure1604for the given {{PROCEDURE}} that sets the field value.1605Usually {{PROCEDURE}} has the same name is <accessor name> (but it1606doesn't have to).16071608=== Libraries16091610Libraries provide a way to organize Scheme programs into reusable parts with1611explicitly defined interfaces to the rest of the program. This section defines1612the notation and semantics for libraries.16131614==== Library Syntax16151616A library definition takes the following form:16171618<macro>(define-library <library name> <library declaration> ...)</macro>16191620<library name> is a list whose members are identifiers and exact non-negative1621integers. It is used to identify the library uniquely when importing from other1622programs or libraries. Libraries whose first identifier is scheme are reserved1623for use by this report and future versions of this report. Libraries whose1624first identifier is srfi are reserved for libraries implementing Scheme1625Requests for Implementation. It is inadvisable, but not an error, for1626identifiers in library names to contain any of the characters | \ ? * < " : > +1627[ ] / or control characters after escapes are expanded.16281629A <library declaration> is any of:16301631* {{(export <export spec> ...)}}16321633* {{(export-all)}}16341635* {{(import <import set> ...)}}16361637* {{(begin <command or definition> ...)}}16381639* {{(include <filename[1]> <filename[2]> ...)}}16401641* {{(include-ci <filename[1]> <filename[2]> ...)}}16421643* {{(include-library-declarations <filename[1]> <filename[2]> ...)}}16441645* {{(cond-expand <ce-clause[1]> <ce-clause[2]> ...}}16461647An export declaration specifies a list of identifiers which can be made visible1648to other libraries or programs. An <export spec> takes one of the following1649forms:16501651* <identifier>16521653* {{(rename <identifier[1]> <identifier[2]>)}}16541655In an <export spec>, an <identifier> names a single binding defined within or1656imported into the library, where the external name for the export is the same1657as the name of the binding within the library. A {{rename}} spec exports the1658binding defined within or imported into the library and named by <identifier1659[1]> in each {{(<identifier[1]> <identifier[2]>)}} pairing, using <identifier[2]>1660as the external name.16611662As an extension to R7RS, CHICKEN allows the {{(export-all)}} specifier,1663which exports all defined entities to be visible when importing the1664library.16651666An import declaration provides a way to import the identifiers exported by1667another library.16681669The {{begin}}, {{include}}, and {{include}}-ci declarations are used to specify the body of1670the library. They have the same syntax and semantics as the corresponding1671expression types. This form of begin is analogous to, but not the same as, the1672two types of begin defined in section 4.2.3.16731674The {{include-library-declarations}} declaration is similar to {{include}} except that1675the contents of the file are spliced directly into the current library1676definition. This can be used, for example, to share the same export declaration1677among multiple libraries as a simple form of library interface.16781679The {{cond-expand}} declaration has the same syntax and semantics as the1680{{cond-expand}} expression type, except that it expands to spliced-in library1681declarations rather than expressions enclosed in begin.16821683One possible implementation of libraries is as follows: After all {{cond-expand}}1684library declarations are expanded, a new environment is constructed for the1685library consisting of all imported bindings. The expressions from all begin,1686{{include}} and {{include-ci}} library declarations are expanded in that environment in1687the order in which they occur in the library. Alternatively, {{cond-expand}} and1688{{import}} declarations may be processed in left to right order interspersed with1689the processing of other declarations, with the environment growing as imported1690bindings are added to it by each import declaration.16911692When a library is loaded, its expressions are executed in textual order. If a1693library's definitions are referenced in the expanded form of a program or1694library body, then that library must be loaded before the expanded program or1695library body is evaluated. This rule applies transitively. If a library is1696imported by more than one program or library, it may possibly be loaded1697additional times.16981699Similarly, during the expansion of a library (foo), if any syntax keywords1700imported from another library (bar) are needed to expand the library, then the1701library (bar) must be expanded and its syntax definitions evaluated before the1702expansion of (foo).170317041705== Standard procedures17061707This chapter describes Scheme's built-in procedures. The initial (or1708"top level") Scheme environment starts out with a number of variables1709bound to locations containing useful values, most of which are1710primitive procedures that manipulate data. For example, the variable1711abs is bound to (a location initially containing) a procedure of one1712argument that computes the absolute value of a number, and the variable1713+ is bound to a procedure that computes sums. Built-in procedures that1714can easily be written in terms of other built-in procedures are1715identified as "library procedures".17161717A program may use a top-level definition to bind any variable. It may1718subsequently alter any such binding by an assignment (see1719[[#assignments|assignments]], above). These operations do1720not modify the behavior of Scheme's built-in procedures. Altering any1721top-level binding that has not been introduced by a definition has an1722unspecified effect on the behavior of the built-in procedures.17231724=== Equivalence predicates17251726A predicate is a procedure that always returns a boolean value (#t or #f).1727An equivalence predicate is the computational analogue of a1728mathematical equivalence relation (it is symmetric, reflexive, and1729transitive). Of the equivalence predicates described in this section,1730eq? is the finest or most discriminating, and equal? is the coarsest.1731eqv? is slightly less discriminating than eq?.17321733<procedure>(eqv? obj[1] obj[2])</procedure><br>17341735The eqv? procedure defines a useful equivalence relation on objects.1736Briefly, it returns #t if obj[1] and obj[2] should normally be regarded1737as the same object. This relation is left slightly open to1738interpretation, but the following partial specification of eqv? holds1739for all implementations of Scheme.17401741The eqv? procedure returns #t if:17421743* obj[1] and obj[2] are both #t or both #f.17441745* obj[1] and obj[2] are both symbols and17461747 (string=? (symbol->string obj1)1748 (symbol->string obj2))1749 ===> #t17501751Note: This assumes that neither obj[1] nor obj[2] is an "uninterned1752symbol" as alluded to in the section on [[#symbols|symbols]]. This1753report does not presume to specify the behavior of eqv? on1754implementation-dependent extensions.17551756* obj[1] and obj[2] are both numbers, are numerically equal (see =,1757 under [[#numerical-operations|numerical operations]]), and are1758 either both exact or both inexact.17591760* obj[1] and obj[2] are both characters and are the same character1761 according to the char=? procedure (see "[[#characters|characters]]").17621763* both obj[1] and obj[2] are the empty list.17641765* obj[1] and obj[2] are pairs, vectors, or strings that denote the1766 same locations in the store.17671768* obj[1] and obj[2] are procedures whose location tags are equal1769 (see "[[#procedures|procedures]]").17701771The eqv? procedure returns #f if:17721773* obj[1] and obj[2] are of different types.17741775* one of obj[1] and obj[2] is #t but the other is #f.17761777* obj[1] and obj[2] are symbols but17781779 (string=? (symbol->string obj[1])1780 (symbol->string obj[2]))1781 ===> #f17821783* one of obj[1] and obj[2] is an exact number but the other is an1784 inexact number.17851786* obj[1] and obj[2] are numbers for which the = procedure returns #f.17871788* obj[1] and obj[2] are characters for which the char=? procedure1789 returns #f.17901791* one of obj[1] and obj[2] is the empty list but the other is not.17921793* obj[1] and obj[2] are pairs, vectors, or strings that denote1794 distinct locations.17951796* obj[1] and obj[2] are procedures that would behave differently1797 (return different value(s) or have different side effects) for some1798 arguments.17991800 (eqv? 'a 'a) ===> #t1801 (eqv? 'a 'b) ===> #f1802 (eqv? 2 2) ===> #t1803 (eqv? '() '()) ===> #t1804 (eqv? 100000000 100000000) ===> #t1805 (eqv? (cons 1 2) (cons 1 2)) ===> #f1806 (eqv? (lambda () 1)1807 (lambda () 2)) ===> #f1808 (eqv? #f 'nil) ===> #f1809 (let ((p (lambda (x) x)))1810 (eqv? p p)) ===> #t18111812The following examples illustrate cases in which the above rules do not1813fully specify the behavior of eqv?. All that can be said about such1814cases is that the value returned by eqv? must be a boolean.18151816 (eqv? "" "") ===> unspecified1817 (eqv? '#() '#()) ===> unspecified1818 (eqv? (lambda (x) x)1819 (lambda (x) x)) ===> unspecified1820 (eqv? (lambda (x) x)1821 (lambda (y) y)) ===> unspecified18221823The next set of examples shows the use of eqv? with procedures that1824have local state. Gen-counter must return a distinct procedure every1825time, since each procedure has its own internal counter. Gen-loser,1826however, returns equivalent procedures each time, since the local state1827does not affect the value or side effects of the procedures.18281829 (define gen-counter1830 (lambda ()1831 (let ((n 0))1832 (lambda () (set! n (+ n 1)) n))))1833 (let ((g (gen-counter)))1834 (eqv? g g)) ===> #t1835 (eqv? (gen-counter) (gen-counter))1836 ===> #f1837 (define gen-loser1838 (lambda ()1839 (let ((n 0))1840 (lambda () (set! n (+ n 1)) 27))))1841 (let ((g (gen-loser)))1842 (eqv? g g)) ===> #t1843 (eqv? (gen-loser) (gen-loser))1844 ===> unspecified18451846 (letrec ((f (lambda () (if (eqv? f g) 'both 'f)))1847 (g (lambda () (if (eqv? f g) 'both 'g))))1848 (eqv? f g))1849 ===> unspecified18501851 (letrec ((f (lambda () (if (eqv? f g) 'f 'both)))1852 (g (lambda () (if (eqv? f g) 'g 'both))))1853 (eqv? f g))1854 ===> #f18551856Since it is an error to modify constant objects (those returned by1857literal expressions), implementations are permitted, though not1858required, to share structure between constants where appropriate. Thus1859the value of eqv? on constants is sometimes implementation-dependent.18601861 (eqv? '(a) '(a)) ===> unspecified1862 (eqv? "a" "a") ===> unspecified1863 (eqv? '(b) (cdr '(a b))) ===> unspecified1864 (let ((x '(a)))1865 (eqv? x x)) ===> #t18661867Rationale: The above definition of eqv? allows implementations1868latitude in their treatment of procedures and literals:1869implementations are free either to detect or to fail to detect that1870two procedures or two literals are equivalent to each other, and1871can decide whether or not to merge representations of equivalent1872objects by using the same pointer or bit pattern to represent both.18731874<procedure>(eq? obj[1] obj[2])</procedure><br>18751876Eq? is similar to eqv? except that in some cases it is capable of1877discerning distinctions finer than those detectable by eqv?.18781879Eq? and eqv? are guaranteed to have the same behavior on symbols,1880booleans, the empty list, pairs, procedures, and non-empty strings and1881vectors. Eq?'s behavior on numbers and characters is1882implementation-dependent, but it will always return either true or1883false, and will return true only when eqv? would also return true. Eq?1884may also behave differently from eqv? on empty vectors and empty1885strings.18861887 (eq? 'a 'a) ===> #t1888 (eq? '(a) '(a)) ===> unspecified1889 (eq? (list 'a) (list 'a)) ===> #f1890 (eq? "a" "a") ===> unspecified1891 (eq? "" "") ===> unspecified1892 (eq? '() '()) ===> #t1893 (eq? 2 2) ===> unspecified1894 (eq? #\A #\A) ===> unspecified1895 (eq? car car) ===> #t1896 (let ((n (+ 2 3)))1897 (eq? n n)) ===> unspecified1898 (let ((x '(a)))1899 (eq? x x)) ===> #t1900 (let ((x '#()))1901 (eq? x x)) ===> #t1902 (let ((p (lambda (x) x)))1903 (eq? p p)) ===> #t19041905Rationale: It will usually be possible to implement eq? much more1906efficiently than eqv?, for example, as a simple pointer comparison1907instead of as some more complicated operation. One reason is that1908it may not be possible to compute eqv? of two numbers in constant1909time, whereas eq? implemented as pointer comparison will always1910finish in constant time. Eq? may be used like eqv? in applications1911using procedures to implement objects with state since it obeys the1912same constraints as eqv?.19131914<procedure>(equal? obj[1] obj[2])</procedure><br>19151916Equal? recursively compares the contents of pairs, vectors, and1917strings, applying eqv? on other objects such as numbers and symbols. A1918rule of thumb is that objects are generally equal? if they print the1919same. Equal? may fail to terminate if its arguments are circular data1920structures.19211922 (equal? 'a 'a) ===> #t1923 (equal? '(a) '(a)) ===> #t1924 (equal? '(a (b) c)1925 '(a (b) c)) ===> #t1926 (equal? "abc" "abc") ===> #t1927 (equal? 2 2) ===> #t1928 (equal? (make-vector 5 'a)1929 (make-vector 5 'a)) ===> #t1930 (equal? (lambda (x) x)1931 (lambda (y) y)) ===> unspecified19321933=== Numbers19341935Numerical computation has traditionally been neglected by the Lisp1936community. Until Common Lisp there was no carefully thought out1937strategy for organizing numerical computation, and with the exception1938of the MacLisp system [20] little effort was made to execute numerical1939code efficiently. This report recognizes the excellent work of the1940Common Lisp committee and accepts many of their recommendations. In1941some ways this report simplifies and generalizes their proposals in a1942manner consistent with the purposes of Scheme.19431944It is important to distinguish between the mathematical numbers, the1945Scheme numbers that attempt to model them, the machine representations1946used to implement the Scheme numbers, and notations used to write1947numbers. This report uses the types number, complex, real, rational,1948and integer to refer to both mathematical numbers and Scheme numbers.1949Machine representations such as fixed point and floating point are1950referred to by names such as fixnum and flonum.19511952==== Numerical types19531954Mathematically, numbers may be arranged into a tower of subtypes in1955which each level is a subset of the level above it:19561957 number1958 complex1959 real1960 rational1961 integer19621963For example, 3 is an integer. Therefore 3 is also a rational, a real,1964and a complex. The same is true of the Scheme numbers that model 3. For1965Scheme numbers, these types are defined by the predicates number?,1966complex?, real?, rational?, and integer?.19671968There is no simple relationship between a number's type and its1969representation inside a computer. Although most implementations of1970Scheme will offer at least two different representations of 3, these1971different representations denote the same integer.19721973Scheme's numerical operations treat numbers as abstract data, as1974independent of their representation as possible. Although an1975implementation of Scheme may use fixnum, flonum, and perhaps other1976representations for numbers, this should not be apparent to a casual1977programmer writing simple programs.19781979It is necessary, however, to distinguish between numbers that are1980represented exactly and those that may not be. For example, indexes1981into data structures must be known exactly, as must some polynomial1982coefficients in a symbolic algebra system. On the other hand, the1983results of measurements are inherently inexact, and irrational numbers1984may be approximated by rational and therefore inexact approximations.1985In order to catch uses of inexact numbers where exact numbers are1986required, Scheme explicitly distinguishes exact from inexact numbers.1987This distinction is orthogonal to the dimension of type.19881989==== Exactness19901991Scheme numbers are either exact or inexact. A number is exact if it was1992written as an exact constant or was derived from exact numbers using1993only exact operations. A number is inexact if it was written as an1994inexact constant, if it was derived using inexact ingredients, or if it1995was derived using inexact operations. Thus inexactness is a contagious1996property of a number. If two implementations produce exact results for1997a computation that did not involve inexact intermediate results, the1998two ultimate results will be mathematically equivalent. This is1999generally not true of computations involving inexact numbers since2000approximate methods such as floating point arithmetic may be used, but2001it is the duty of each implementation to make the result as close as2002practical to the mathematically ideal result.20032004Rational operations such as + should always produce exact results when2005given exact arguments. If the operation is unable to produce an exact2006result, then it may either report the violation of an implementation2007restriction or it may silently coerce its result to an inexact value.2008See [[#implementation-restrictions|the next section]].20092010With the exception of inexact->exact, the operations described in this2011section must generally return inexact results when given any inexact2012arguments. An operation may, however, return an exact result if it can2013prove that the value of the result is unaffected by the inexactness of2014its arguments. For example, multiplication of any number by an exact2015zero may produce an exact zero result, even if the other argument is2016inexact.20172018==== Implementation restrictions20192020Implementations of Scheme are not required to implement the whole2021tower of subtypes given under "[[#Numerical types|Numerical types]]",2022but they must implement a coherent subset consistent with both the2023purposes of the implementation and the spirit of the Scheme2024language. For example, an implementation in which all numbers are real2025may still be quite useful.20262027Implementations may also support only a limited range of numbers of any2028type, subject to the requirements of this section. The supported range2029for exact numbers of any type may be different from the supported range2030for inexact numbers of that type. For example, an implementation that2031uses flonums to represent all its inexact real numbers may support a2032practically unbounded range of exact integers and rationals while2033limiting the range of inexact reals (and therefore the range of inexact2034integers and rationals) to the dynamic range of the flonum format.2035Furthermore the gaps between the representable inexact integers and2036rationals are likely to be very large in such an implementation as the2037limits of this range are approached.20382039An implementation of Scheme must support exact integers throughout the2040range of numbers that may be used for indexes of lists, vectors, and2041strings or that may result from computing the length of a list, vector,2042or string. The length, vector-length, and string-length procedures must2043return an exact integer, and it is an error to use anything but an2044exact integer as an index. Furthermore any integer constant within the2045index range, if expressed by an exact integer syntax, will indeed be2046read as an exact integer, regardless of any implementation restrictions2047that may apply outside this range. Finally, the procedures listed below2048will always return an exact integer result provided all their arguments2049are exact integers and the mathematically expected result is2050representable as an exact integer within the implementation:20512052 - *2053 + abs2054 ceiling denominator2055 exact-integer-sqrt expt2056 floor floor/2057 floor-quotient floor-remainder2058 gcd lcm2059 max min2060 modulo numerator2061 quotient rationalize2062 remainder round2063 square truncate2064 truncate/ truncate-quotient2065 truncate-remainder20662067CHICKEN follows the IEEE 32-bit and 64-bit floating point2068standards on all supported platforms.20692070It is the programmer's responsibility to avoid using inexact number objects2071with magnitude or significand too large to be represented in the2072implementation.20732074In addition, implementations may distinguish special numbers called positive2075infinity, negative infinity, NaN, and negative zero.20762077Positive infinity is regarded as an inexact real (but not rational) number that2078represents an indeterminate value greater than the numbers represented by all2079rational numbers. Negative infinity is regarded as an inexact real (but not2080rational) number that represents an indeterminate value less than the numbers2081represented by all rational numbers.20822083Adding or multiplying an infinite value by any finite real value results in an2084appropriately signed infinity; however, the sum of positive and negative2085infinities is a NaN. Positive infinity is the reciprocal of zero, and negative2086infinity is the reciprocal of negative zero. The behavior of the transcendental2087functions is sensitive to infinity in accordance with IEEE 754.20882089A NaN is regarded as an inexact real (but not rational) number so indeterminate2090that it might represent any real value, including positive or negative2091infinity, and might even be greater than positive infinity or less than2092negative infinity. An implementation that does not support non-real numbers may2093use NaN to represent non-real values like (sqrt -1.0) and (asin 2.0).20942095A NaN always compares false to any number, including a NaN. An arithmetic2096operation where one operand is NaN returns NaN, unless the implementation can2097prove that the result would be the same if the NaN were replaced by any2098rational number. Dividing zero by zero results in NaN unless both zeros are2099exact.21002101Negative zero is an inexact real value written -0.0 and is distinct (in the2102sense of eqv?) from 0.0. A Scheme implementation is not required to distinguish2103negative zero. If it does, however, the behavior of the transcendental2104functions is sensitive to the distinction in accordance with IEEE 754.2105Specifically, in a Scheme implementing both complex numbers and negative zero,2106the branch cut of the complex logarithm function is such that (imag-part (log2107-1.0-0.0i)) is --π rather than π.21082109Furthermore, the negation of negative zero is ordinary zero and vice versa.2110This implies that the sum of two or more negative zeros is negative, and the2111result of subtracting (positive) zero from a negative zero is likewise2112negative. However, numerical comparisons treat negative zero as equal to zero.21132114Note that both the real and the imaginary parts of a complex number can be2115infinities, NaNs, or negative zero.211621172118==== Syntax of numerical constants21192120For a complete formal description of the syntax of the written2121representations for numbers, see the R7RS report. Note that case is2122not significant in numerical constants.21232124A number may be written in binary, octal, decimal, or hexadecimal by2125the use of a radix prefix. The radix prefixes are #b (binary), #o2126(octal), #d (decimal), and #x (hexadecimal). With no radix prefix, a2127number is assumed to be expressed in decimal.21282129A numerical constant may be specified to be either exact or inexact by2130a prefix. The prefixes are #e for exact, and #i for inexact. An2131exactness prefix may appear before or after any radix prefix that is2132used. If the written representation of a number has no exactness2133prefix, the constant may be either inexact or exact. It is inexact if2134it contains a decimal point, an exponent, or a "#" character in the2135place of a digit, otherwise it is exact. In systems with inexact2136numbers of varying precisions it may be useful to specify the precision2137of a constant. For this purpose, numerical constants may be written2138with an exponent marker that indicates the desired precision of the2139inexact representation. The letters s, f, d, and l specify the use of2140short, single, double, and long precision, respectively. (When fewer2141than four internal inexact representations exist, the four size2142specifications are mapped onto those available. For example, an2143implementation with two internal representations may map short and2144single together and long and double together.) In addition, the2145exponent marker e specifies the default precision for the2146implementation. The default precision has at least as much precision as2147double, but implementations may wish to allow this default to be set by2148the user.21492150 3.14159265358979F02151 Round to single --- 3.1415932152 0.6L02153 Extend to long --- .60000000000000021542155==== Numerical operations21562157The numerical routines described below have argument restrictions,2158which are encoded in the naming conventions of the arguments as2159given in the procedure's signature. The conventions are as follows:21602161; {{obj}} : any object2162; {{list, list1, ... listj, ... list}} : (see "[[#pairs-and-lists|Pairs and lists]]" below)2163; {{z, z1, ... zj, ...}} : complex number2164; {{x, x1, ... xj, ...}} : real number2165; {{y, y1, ... yj, ...}} : real number2166; {{q, q1, ... qj, ...}} : rational number2167; {{n, n1, ... nj, ...}} : integer2168; {{k, k1, ... kj, ...}} : exact non-negative integer21692170The examples used in this section assume that any2171numerical constant written using an exact notation is indeed2172represented as an exact number. Some examples also assume that certain2173numerical constants written using an inexact notation can be2174represented without loss of accuracy; the inexact constants were chosen2175so that this is likely to be true in implementations that use flonums2176to represent inexact numbers.21772178<procedure>(number? obj)</procedure><br>2179<procedure>(complex? obj)</procedure><br>2180<procedure>(real? obj)</procedure><br>2181<procedure>(rational? obj)</procedure><br>2182<procedure>(integer? obj)</procedure><br>21832184These numerical type predicates can be applied to any kind of argument,2185including non-numbers. They return #t if the object is of the named2186type, and otherwise they return #f. In general, if a type predicate is2187true of a number then all higher type predicates are also true of that2188number. Consequently, if a type predicate is false of a number, then2189all lower type predicates are also false of that number. If z is an2190inexact complex number, then (real? z) is true if and only if (zero?2191(imag-part z)) is true. If x is an inexact real number, then (integer?2192x) is true if and only if (= x (round x)).21932194 (complex? 3+4i) ===> #t2195 (complex? 3) ===> #t2196 (real? 3) ===> #t2197 (real? -2.5+0.0i) ===> #t2198 (real? #e1e10) ===> #t2199 (rational? 6/10) ===> #t2200 (rational? 6/3) ===> #t2201 (integer? 3+0i) ===> #t2202 (integer? 3.0) ===> #t2203 (integer? 8/4) ===> #t22042205Note: The behavior of these type predicates on inexact numbers is2206unreliable, since any inaccuracy may affect the result.22072208Note: In many implementations the rational? procedure will be the2209same as real?, and the complex? procedure will be the same as2210number?, but unusual implementations may be able to represent some2211irrational numbers exactly or may extend the number system to2212support some kind of non-complex numbers.22132214<procedure>(exact? z)</procedure><br>2215<procedure>(inexact? z)</procedure><br>22162217These numerical predicates provide tests for the exactness of a2218quantity. For any Scheme number, precisely one of these predicates is2219true.22202221<procedure>(exact-integer? z)</procedure>22222223Returns #t if z is both exact and an integer; otherwise returns #f.22242225 (exact-integer? 32) ===> #t2226 (exact-integer? 32.0) ===> #f2227 (exact-integer? 32/5) ===> #f22282229<procedure>(= z[1] z[2] z[3] ...)</procedure><br>2230<procedure>(< x[1] x[2] x[3] ...)</procedure><br>2231<procedure>(> x[1] x[2] x[3] ...)</procedure><br>2232<procedure>(<= x[1] x[2] x[3] ...)</procedure><br>2233<procedure>(>= x[1] x[2] x[3] ...)</procedure><br>22342235These procedures return #t if their arguments are (respectively):2236equal, monotonically increasing, monotonically decreasing,2237monotonically nondecreasing, or monotonically nonincreasing.22382239These predicates are required to be transitive.22402241Note: The traditional implementations of these predicates in2242Lisp-like languages are not transitive.22432244Note: While it is not an error to compare inexact numbers using2245these predicates, the results may be unreliable because a small2246inaccuracy may affect the result; this is especially true of = and2247zero?. When in doubt, consult a numerical analyst.22482249<procedure>(zero? z)</procedure><br>2250<procedure>(positive? x)</procedure><br>2251<procedure>(negative? x)</procedure><br>2252<procedure>(odd? n)</procedure><br>2253<procedure>(even? n)</procedure><br>22542255These numerical predicates test a number for a particular property,2256returning #t or #f. See note above.22572258<procedure>(max x[1] x[2] ...)</procedure><br>2259<procedure>(min x[1] x[2] ...)</procedure><br>22602261These procedures return the maximum or minimum of their arguments.22622263 (max 3 4) ===> 4 ; exact2264 (max 3.9 4) ===> 4.0 ; inexact22652266Note: If any argument is inexact, then the result will also be2267inexact (unless the procedure can prove that the inaccuracy is not2268large enough to affect the result, which is possible only in2269unusual implementations). If min or max is used to compare numbers2270of mixed exactness, and the numerical value of the result cannot be2271represented as an inexact number without loss of accuracy, then the2272procedure may report a violation of an implementation restriction.22732274<procedure>(+ z[1] ...)</procedure><br>2275<procedure>(* z[1] ...)</procedure><br>22762277These procedures return the sum or product of their arguments.22782279 (+ 3 4) ===> 72280 (+ 3) ===> 32281 (+) ===> 02282 (* 4) ===> 42283 (*) ===> 122842285<procedure>(- z[1] z[2])</procedure><br>2286<procedure>(- z)</procedure><br>2287<procedure>(- z[1] z[2] ...)</procedure><br>2288<procedure>(/ z[1] z[2])</procedure><br>2289<procedure>(/ z)</procedure><br>2290<procedure>(/ z[1] z[2] ...)</procedure><br>22912292With two or more arguments, these procedures return the difference or2293quotient of their arguments, associating to the left. With one2294argument, however, they return the additive or multiplicative inverse2295of their argument.22962297 (- 3 4) ===> -12298 (- 3 4 5) ===> -62299 (- 3) ===> -32300 (/ 3 4 5) ===> 3/202301 (/ 3) ===> 1/323022303<procedure>(abs x)</procedure><br>23042305Abs returns the absolute value of its argument.23062307 (abs -7) ===> 723082309<procedure>(floor/ n[1] n[2])</procedure><br>2310<procedure>(floor-quotient n[1] n[2])</procedure><br>2311<procedure>(floor-remainder n[1] n[2])</procedure><br>2312<procedure>(truncate/ n[1] n[2])</procedure><br>2313<procedure>(truncate-quotient n[1] n[2])</procedure><br>2314<procedure>(truncate-remainder n[1] n[2])</procedure><br>23152316These procedures implement number-theoretic (integer) division. It is an error2317if n[2] is zero. The procedures ending in / return two integers; the other2318procedures return an integer. All the procedures compute a quotient n[q] and remainder2319n[r] such that n[1] = n[2] * n[q] + n[r]. For each of the division operators, there are three procedures defined as2320follows:23212322 (<operator>/ n[1] n[2]) ==> n[q] n[r]2323 (<operator>-quotient n[1] n[2]) ==> n[q]2324 (<operator>-remainder n[1] n[2]) ==> n[r]23252326The remainder n[r] is determined by the choice of integer n[q]: n[r] = n[1] -- n[2] * n[q]. Each set of operators uses a different choice of n[q]:23272328 floor n[q] = ⌊n[1] / n[2]⌋2329 truncate n[q] = runcate(n[1] / n[2])23302331For any of the operators, and for integers n[1] and n[2] with n[2] not equal to 0,23322333 (= n[1] (+ (* n[2] (<operator>-quotient n[1] n[2]))2334 (<operator>-remainder n[1] n[2])))2335 ==> #t23362337provided all numbers involved in that computation are exact.23382339Examples:23402341 (floor/ 5 2) ==> 2 12342 (floor/ -5 2) ==> -3 12343 (floor/ 5 -2) ==> -3 -12344 (floor/ -5 -2) ==> 2 -12345 (truncate/ 5 2) ==> 2 12346 (truncate/ -5 2) ==> -2 -12347 (truncate/ 5 -2) ==> -2 12348 (truncate/ -5 -2) ==> 2 -12349 (truncate/ -5.0 -2) ==> 2.0 -1.023502351<procedure>(quotient n[1] n[2])</procedure><br>2352<procedure>(remainder n[1] n[2])</procedure><br>2353<procedure>(modulo n[1] n[2])</procedure><br>23542355These procedures implement number-theoretic (integer) division. n[2]2356should be non-zero. All three procedures return integers. If n[1]/n[2]2357is an integer:23582359 (quotient n[1] n[2]) ===> n[1]/n[2]2360 (remainder n[1] n[2]) ===> 02361 (modulo n[1] n[2]) ===> 023622363If n[1]/n[2] is not an integer:23642365 (quotient n[1] n[2]) ===> n[q]2366 (remainder n[1] n[2]) ===> n[r]2367 (modulo n[1] n[2]) ===> n[m]23682369where n[q] is n[1]/n[2] rounded towards zero, 0 < |n[r]| < |n[2]|, 0 <2370|n[m]| < |n[2]|, n[r] and n[m] differ from n[1] by a multiple of n[2],2371n[r] has the same sign as n[1], and n[m] has the same sign as n[2].23722373From this we can conclude that for integers n[1] and n[2] with n[2] not2374equal to 0,23752376 (= n[1] (+ (* n[2] (quotient n[1] n[2]))2377 (remainder n[1] n[2])))2378 ===> #t23792380provided all numbers involved in that computation are exact.23812382 (modulo 13 4) ===> 12383 (remainder 13 4) ===> 123842385 (modulo -13 4) ===> 32386 (remainder -13 4) ===> -123872388 (modulo 13 -4) ===> -32389 (remainder 13 -4) ===> 123902391 (modulo -13 -4) ===> -12392 (remainder -13 -4) ===> -123932394 (remainder -13 -4.0) ===> -1.0 ; inexact23952396<procedure>(gcd n[1] ...)</procedure><br>2397<procedure>(lcm n[1] ...)</procedure><br>23982399These procedures return the greatest common divisor or least common2400multiple of their arguments. The result is always non-negative.24012402 (gcd 32 -36) ===> 42403 (gcd) ===> 02404 (lcm 32 -36) ===> 2882405 (lcm 32.0 -36) ===> 288.0 ; inexact2406 (lcm) ===> 124072408<procedure>(numerator q)</procedure><br>2409<procedure>(denominator q)</procedure><br>24102411These procedures return the numerator or denominator of their argument;2412the result is computed as if the argument was represented as a fraction2413in lowest terms. The denominator is always positive. The denominator of24140 is defined to be 1.24152416 (numerator (/ 6 4)) ===> 32417 (denominator (/ 6 4)) ===> 22418 (denominator2419 (exact->inexact (/ 6 4))) ===> 2.024202421<procedure>(floor x)</procedure><br>2422<procedure>(ceiling x)</procedure><br>2423<procedure>(truncate x)</procedure><br>2424<procedure>(round x)</procedure><br>24252426These procedures return integers. Floor returns the largest integer not2427larger than x. Ceiling returns the smallest integer not smaller than x.2428Truncate returns the integer closest to x whose absolute value is not2429larger than the absolute value of x. Round returns the closest integer2430to x, rounding to even when x is halfway between two integers.24312432Rationale: Round rounds to even for consistency with the default2433rounding mode specified by the IEEE floating point standard.24342435Note: If the argument to one of these procedures is inexact, then2436the result will also be inexact. If an exact value is needed, the2437result should be passed to the inexact->exact procedure.24382439 (floor -4.3) ===> -5.02440 (ceiling -4.3) ===> -4.02441 (truncate -4.3) ===> -4.02442 (round -4.3) ===> -4.024432444 (floor 3.5) ===> 3.02445 (ceiling 3.5) ===> 4.02446 (truncate 3.5) ===> 3.02447 (round 3.5) ===> 4.0 ; inexact24482449 (round 7/2) ===> 4 ; exact2450 (round 7) ===> 724512452<procedure>(rationalize x y)</procedure><br>24532454Rationalize returns the simplest rational number differing from x by no2455more than y. A rational number r[1] is simpler than another rational2456number r[2] if r[1] = p[1]/q[1] and r[2] = p[2]/q[2] (in lowest terms)2457and |p[1]| < |p[2]| and |q[1]| < |q[2]|. Thus 3/5 is simpler than 4/7.2458Although not all rationals are comparable in this ordering (consider 2/24597 and 3/5) any interval contains a rational number that is simpler than2460every other rational number in that interval (the simpler 2/5 lies2461between 2/7 and 3/5). Note that 0 = 0/1 is the simplest rational of2462all.24632464 (rationalize2465 (inexact->exact .3) 1/10) ===> 1/3 ; exact2466 (rationalize .3 1/10) ===> #i1/3 ; inexact24672468<procedure>(square z)</procedure>24692470Returns the square of z. This is equivalent to {{(* z z)}}-24712472 (square 42) ==> 17642473 (square 2.0) ==> 4.024742475<procedure>(exact-integer-sqrt k)</procedure>24762477Returns two non-negative exact integers s and r where k = s^2 + r and k < (s + 1)^2.24782479 (exact-integer-sqrt 4) ==> 2 02480 (exact-integer-sqrt 5) ==> 2 124812482<procedure>(expt z[1] z[2])</procedure><br>24832484Returns z[1] raised to the power z[2]. For z[1] != 024852486 z[1]^z[2] = e^z[2] log z[1]248724880^z is 1 if z = 0 and 0 otherwise.24892490<procedure>(exact z)</procedure><br>2491<procedure>(inexact z)</procedure><br>24922493The procedure {{inexact}} returns an inexact representation of z. The value returned is the inexact number that is numerically closest to the2494argument. For inexact arguments, the result is the same as the argument. For2495exact complex numbers, the result is a complex number whose real and imaginary2496parts are the result of applying inexact to the real and imaginary parts of the2497argument, respectively. If an exact argument has no reasonably close inexact2498equivalent (in the sense of =), then a violation of an implementation2499restriction may be reported.25002501The procedure {{exact}} returns an exact representation of z. The value returned is the exact number that is numerically closest to the2502argument. For exact arguments, the result is the same as the argument. For2503inexact non-integral real arguments, the implementation may return a rational2504approximation, or may report an implementation violation. For inexact complex2505arguments, the result is a complex number whose real and imaginary parts are2506the result of applying exact to the real and imaginary parts of the argument,2507respectively. If an inexact argument has no reasonably close exact equivalent,2508(in the sense of =), then a violation of an implementation restriction may be2509reported.25102511==== Numerical input and output25122513<procedure>(number->string z [radix])</procedure>25142515Radix must be an exact integer. The R7RS standard only requires2516implementations to support 2, 8, 10, or 16, but CHICKEN allows any2517radix between 2 and 36, inclusive (note: due to a bug, flonums with2518fractional components always use radix 10, irrespective of the argument).2519If omitted, radix defaults to 10. The procedure number->string takes2520a number and a radix and returns as a string an external2521representation of the given number in the given radix such that25222523 (let ((number number)2524 (radix radix))2525 (eqv? number2526 (string->number (number->string number2527 radix)2528 radix)))25292530is true. It is an error if no possible result makes this expression2531true.25322533If z is inexact, the radix is 10, and the above expression can be2534satisfied by a result that contains a decimal point, then the result2535contains a decimal point and is expressed using the minimum number of2536digits (exclusive of exponent and trailing zeroes) needed to make the2537above expression true [3, 5]; otherwise the format of the result is2538unspecified.25392540The result returned by number->string never contains an explicit radix2541prefix.25422543Note: The error case can occur only when z is not a complex2544number or is a complex number with a non-rational real or imaginary2545part.25462547Rationale: If z is an inexact number represented using flonums,2548and the radix is 10, then the above expression is normally2549satisfied by a result containing a decimal point. The unspecified2550case allows for infinities, NaNs, and non-flonum representations.25512552As an extension to R7RS, CHICKEN supports reading and writing the2553special IEEE floating-point numbers ''+nan'', ''+inf'' and ''-inf'',2554as well as negative zero.25552556<procedure>(string->number string)</procedure><br>2557<procedure>(string->number string radix)</procedure><br>25582559Returns a number of the maximally precise representation expressed by2560the given string. Radix must be an exact integer. The R7RS standard2561only requires implementations to support 2, 8, 10, or 16, but CHICKEN2562allows any radix between 2 and 36, inclusive. If supplied, radix is a2563default radix that may be overridden by an explicit radix prefix in2564string (e.g. "#o177"). If radix is not supplied, then the default2565radix is 10. If string is not a syntactically valid notation for a2566number, then string->number returns #f.25672568If the radix is higher than 18, the parser treats ambiguous syntax2569that might be a complex number, like {{{"+i"}}} and {{{"-i"}}} (and2570any prefixes like {{{"+1234i"}}}), as an integer. If you want this to2571be parsed as a complex number, explicitly write down {{{"0+i"}}} to2572disambiguate. Note that {{{number->string}}} will always emit complex2573numbers using the full notation, so it can always be read back by2574{{{string->number}}}.25752576 (string->number "100") ===> 1002577 (string->number "100" 16) ===> 2562578 (string->number "1e2") ===> 100.02579 (string->number "15##") ===> 1500.025802581Note: The domain of string->number may be restricted by2582implementations in the following ways. String->number is permitted2583to return #f whenever string contains an explicit radix prefix. If2584all numbers supported by an implementation are real, then string->2585number is permitted to return #f whenever string uses the polar or2586rectangular notations for complex numbers. If all numbers are2587integers, then string->number may return #f whenever the fractional2588notation is used. If all numbers are exact, then string->number may2589return #f whenever an exponent marker or explicit exactness prefix2590is used, or if a # appears in place of a digit. If all inexact2591numbers are integers, then string->number may return #f whenever a2592decimal point is used.25932594=== Other data types25952596This section describes operations on some of Scheme's non-numeric data2597types: booleans, pairs, lists, symbols, characters, strings and2598vectors.25992600==== Booleans26012602The standard boolean objects for true and false are written as #t and #f.2603What really matters, though, are the objects that the Scheme2604conditional expressions (if, cond, and, or, do) treat as true or false.2605The phrase "a true value" (or sometimes just "true") means any2606object treated as true by the conditional expressions, and the phrase2607"a false value" (or "false") means any object treated as false by2608the conditional expressions.26092610Of all the standard Scheme values, only #f counts as false in2611conditional expressions. Except for #f, all standard Scheme values,2612including #t, pairs, the empty list, symbols, numbers, strings,2613vectors, and procedures, count as true.26142615Note: Programmers accustomed to other dialects of Lisp should be2616aware that Scheme distinguishes both #f and the empty list from the2617symbol nil.26182619Boolean constants evaluate to themselves, so they do not need to be2620quoted in programs.26212622 #t ===> #t2623 #f ===> #f2624 '#f ===> #f26252626<procedure>(not obj)</procedure><br>26272628Not returns #t if obj is false, and returns #f otherwise.26292630 (not #t) ===> #f2631 (not 3) ===> #f2632 (not (list 3)) ===> #f2633 (not #f) ===> #t2634 (not '()) ===> #f2635 (not (list)) ===> #f2636 (not 'nil) ===> #f26372638<procedure>(boolean? obj)</procedure><br>26392640Boolean? returns #t if obj is either #t or #f and returns #f otherwise.26412642 (boolean? #f) ===> #t2643 (boolean? 0) ===> #f2644 (boolean? '()) ===> #f26452646<procedure>(boolean=? boolean[1] boolean[2] boolean[3] ...)</procedure>26472648Returns #t if all the arguments are #t or all are #f.26492650==== Pairs and lists26512652A pair (sometimes called a dotted pair) is a record structure with two2653fields called the car and cdr fields (for historical reasons). Pairs2654are created by the procedure cons. The car and cdr fields are accessed2655by the procedures car and cdr. The car and cdr fields are assigned by2656the procedures set-car! and set-cdr!.26572658Pairs are used primarily to represent lists. A list can be defined2659recursively as either the empty list or a pair whose cdr is a list.2660More precisely, the set of lists is defined as the smallest set X such2661that26622663* The empty list is in X.2664* If list is in X, then any pair whose cdr field contains list is2665 also in X.26662667The objects in the car fields of successive pairs of a list are the2668elements of the list. For example, a two-element list is a pair whose2669car is the first element and whose cdr is a pair whose car is the2670second element and whose cdr is the empty list. The length of a list is2671the number of elements, which is the same as the number of pairs.26722673The empty list is a special object of its own type (it is not a pair);2674it has no elements and its length is zero.26752676Note: The above definitions imply that all lists have finite2677length and are terminated by the empty list.26782679The most general notation (external representation) for Scheme pairs is2680the "dotted" notation (c[1] . c[2]) where c[1] is the value of the2681car field and c[2] is the value of the cdr field. For example (4 . 5)2682is a pair whose car is 4 and whose cdr is 5. Note that (4 . 5) is the2683external representation of a pair, not an expression that evaluates to2684a pair.26852686A more streamlined notation can be used for lists: the elements of the2687list are simply enclosed in parentheses and separated by spaces. The2688empty list is written () . For example,26892690 (a b c d e)26912692and26932694 (a . (b . (c . (d . (e . ())))))26952696are equivalent notations for a list of symbols.26972698A chain of pairs not ending in the empty list is called an improper2699list. Note that an improper list is not a list. The list and dotted2700notations can be combined to represent improper lists:27012702 (a b c . d)27032704is equivalent to27052706 (a . (b . (c . d)))27072708Whether a given pair is a list depends upon what is stored in the cdr2709field. When the set-cdr! procedure is used, an object can be a list one2710moment and not the next:27112712 (define x (list 'a 'b 'c))2713 (define y x)2714 y ===> (a b c)2715 (list? y) ===> #t2716 (set-cdr! x 4) ===> unspecified2717 x ===> (a . 4)2718 (eqv? x y) ===> #t2719 y ===> (a . 4)2720 (list? y) ===> #f2721 (set-cdr! x x) ===> unspecified2722 (list? x) ===> #f27232724Within literal expressions and representations of objects read by the2725read procedure, the forms '<datum>, `<datum>, ,<datum>, and ,@<datum>2726denote two-element lists whose first elements are the symbols quote,2727quasiquote, unquote, and unquote-splicing, respectively. The second2728element in each case is <datum>. This convention is supported so that2729arbitrary Scheme programs may be represented as lists. That is,2730according to Scheme's grammar, every <expression> is also a <datum>.2731Among other things, this permits the use of the read procedure to2732parse Scheme programs.27332734<procedure>(pair? obj)</procedure><br>27352736Pair? returns #t if obj is a pair, and otherwise returns #f.27372738 (pair? '(a . b)) ===> #t2739 (pair? '(a b c)) ===> #t2740 (pair? '()) ===> #f2741 (pair? '#(a b)) ===> #f27422743<procedure>(cons obj[1] obj[2])</procedure><br>27442745Returns a newly allocated pair whose car is obj[1] and whose cdr is2746obj[2]. The pair is guaranteed to be different (in the sense of eqv?)2747from every existing object.27482749 (cons 'a '()) ===> (a)2750 (cons '(a) '(b c d)) ===> ((a) b c d)2751 (cons "a" '(b c)) ===> ("a" b c)2752 (cons 'a 3) ===> (a . 3)2753 (cons '(a b) 'c) ===> ((a b) . c)27542755<procedure>(car pair)</procedure><br>27562757Returns the contents of the car field of pair. Note that it is an error2758to take the car of the empty list.27592760 (car '(a b c)) ===> a2761 (car '((a) b c d)) ===> (a)2762 (car '(1 . 2)) ===> 12763 (car '()) ===> error27642765<procedure>(cdr pair)</procedure><br>27662767Returns the contents of the cdr field of pair. Note that it is an error2768to take the cdr of the empty list.27692770 (cdr '((a) b c d)) ===> (b c d)2771 (cdr '(1 . 2)) ===> 22772 (cdr '()) ===> error27732774<procedure>(set-car! pair obj)</procedure><br>27752776Stores obj in the car field of pair. The value returned by set-car! is2777unspecified.27782779 (define (f) (list 'not-a-constant-list))2780 (define (g) '(constant-list))2781 (set-car! (f) 3) ===> unspecified2782 (set-car! (g) 3) ===> error27832784<procedure>(set-cdr! pair obj)</procedure><br>27852786Stores obj in the cdr field of pair. The value returned by set-cdr! is2787unspecified.27882789<procedure>(null? obj)</procedure><br>27902791Returns #t if obj is the empty list, otherwise returns #f.27922793<procedure>(list? obj)</procedure><br>27942795Returns #t if obj is a list, otherwise returns #f. By definition, all2796lists have finite length and are terminated by the empty list.27972798 (list? '(a b c)) ===> #t2799 (list? '()) ===> #t2800 (list? '(a . b)) ===> #f2801 (let ((x (list 'a)))2802 (set-cdr! x x)2803 (list? x)) ===> #f28042805<procedure>(make-list k [fill])</procedure>28062807Returns a newly allocated list of k elements. If a second argument is given, then each element is initialized to {{fill}}. Otherwise the initial contents of each element is unspecified.28082809 (make-list 2 3) ==> (3 3)28102811<procedure>(list obj ...)</procedure><br>28122813Returns a newly allocated list of its arguments.28142815 (list 'a (+ 3 4) 'c) ===> (a 7 c)2816 (list) ===> ()28172818<procedure>(length list)</procedure><br>28192820Returns the length of list.28212822 (length '(a b c)) ===> 32823 (length '(a (b) (c d e))) ===> 32824 (length '()) ===> 028252826<procedure>(append list ...)</procedure><br>28272828Returns a list consisting of the elements of the first list followed by2829the elements of the other lists.28302831 (append '(x) '(y)) ===> (x y)2832 (append '(a) '(b c d)) ===> (a b c d)2833 (append '(a (b)) '((c))) ===> (a (b) (c))28342835The resulting list is always newly allocated, except that it shares2836structure with the last list argument. The last argument may actually2837be any object; an improper list results if the last argument is not a2838proper list.28392840 (append '(a b) '(c . d)) ===> (a b c . d)2841 (append '() 'a) ===> a28422843<procedure>(reverse list)</procedure><br>28442845Returns a newly allocated list consisting of the elements of list in2846reverse order.28472848 (reverse '(a b c)) ===> (c b a)2849 (reverse '(a (b c) d (e (f))))2850 ===> ((e (f)) d (b c) a)28512852<procedure>(list-tail list k)</procedure><br>28532854Returns the sublist of list obtained by omitting the first k elements.2855It is an error if list has fewer than k elements. List-tail could be2856defined by28572858 (define list-tail2859 (lambda (x k)2860 (if (zero? k)2861 x2862 (list-tail (cdr x) (- k 1)))))28632864<procedure>(list-ref list k)</procedure><br>28652866Returns the kth element of list. (This is the same as the car of2867(list-tail list k).) It is an error if list has fewer than k elements.28682869 (list-ref '(a b c d) 2) ===> c2870 (list-ref '(a b c d)2871 (inexact->exact (round 1.8)))2872 ===> c28732874<procedure>(list-set! list k obj)</procedure>28752876It is an error if k is not a valid index of list.28772878The {{list-set!}} procedure stores obj in element k of list.28792880 (let ((ls (list 'one 'two 'five!)))2881 (list-set! ls 2 'three)2882 ls)2883 ==> (one two three)28842885 (list-set! '(0 1 2) 1 "oops")2886 ==> error ; constant list28872888<procedure>(memq obj list)</procedure><br>2889<procedure>(memv obj list)</procedure><br>2890<procedure>(member obj list [compare])</procedure><br>28912892These procedures return the first sublist of list whose car is obj,2893where the sublists of list are the non-empty lists returned by2894{{(list-tail list k)}} for k less than the length of list. If obj does not2895occur in list, then #f (not the empty list) is returned. {{memq}} uses {{eq?}}2896to compare obj with the elements of list, while {{memv}} uses {{eqv?}} and2897member {{compare}} if given, and {{equal?}} otherwise.28982899 (memq 'a '(a b c)) ===> (a b c)2900 (memq 'b '(a b c)) ===> (b c)2901 (memq 'a '(b c d)) ===> #f2902 (memq (list 'a) '(b (a) c)) ===> #f2903 (member (list 'a)2904 '(b (a) c)) ===> ((a) c)2905 (memq 101 '(100 101 102)) ===> unspecified2906 (memv 101 '(100 101 102)) ===> (101 102)29072908<procedure>(assq obj alist)</procedure><br>2909<procedure>(assv obj alist)</procedure><br>2910<procedure>(assoc obj alist [compare])</procedure><br>29112912Alist (for "association list") must be a list of pairs. These2913procedures find the first pair in alist whose car field is obj, and2914returns that pair. If no pair in alist has obj as its car, then #f (not2915the empty list) is returned. {{assq}} uses {{eq?}} to compare obj with the car2916fields of the pairs in alist, while {{assv}} uses {{eqv?}} and {{assoc}} uses2917{{compare}}, if given, otherwise {{equal?}}.29182919 (define e '((a 1) (b 2) (c 3)))2920 (assq 'a e) ===> (a 1)2921 (assq 'b e) ===> (b 2)2922 (assq 'd e) ===> #f2923 (assq (list 'a) '(((a)) ((b)) ((c))))2924 ===> #f2925 (assoc (list 'a) '(((a)) ((b)) ((c))))2926 ===> ((a))2927 (assq 5 '((2 3) (5 7) (11 13)))2928 ===> unspecified2929 (assv 5 '((2 3) (5 7) (11 13)))2930 ===> (5 7)29312932Rationale: Although they are ordinarily used as predicates, memq,2933memv, member, assq, assv, and assoc do not have question marks in2934their names because they return useful values rather than just #t2935or #f.29362937<procedure>(list-copy obj)</procedure>29382939Returns a newly allocated copy of the given obj if it is a list. Only the pairs themselves are copied; the cars of the result are the same (in the sense of {{eqv?}}) as the cars of list. If obj is an improper list, so is the result, and the final cdrs are the same in2940the sense of {{eqv?}}. An obj which is not a list is returned unchanged. It is an error if2941obj is a circular list.29422943 (define a '(1 8 2 8)) ; a may be immutable2944 (define b (list-copy a))2945 (set-car! b 3) ; b is mutable2946 b ==> (3 8 2 8)2947 a ==> (1 8 2 8)29482949==== Symbols29502951Symbols are objects whose usefulness rests on the fact that two symbols2952are identical (in the sense of eqv?) if and only if their names are2953spelled the same way. This is exactly the property needed to represent2954identifiers in programs, and so most implementations of Scheme use them2955internally for that purpose. Symbols are useful for many other2956applications; for instance, they may be used the way enumerated values2957are used in Pascal.29582959The rules for writing a symbol are exactly the same as the rules for2960writing an identifier.29612962It is guaranteed that any symbol that has been returned as part of a2963literal expression, or read using the read procedure, and subsequently2964written out using the write procedure, will read back in as the2965identical symbol (in the sense of eqv?). The string->symbol procedure,2966however, can create symbols for which this write/read invariance may2967not hold because their names contain special characters or letters in2968the non-standard case.29692970Note: Some implementations of Scheme have a feature known as2971"slashification" in order to guarantee write/read invariance for2972all symbols, but historically the most important use of this2973feature has been to compensate for the lack of a string data type.29742975Some implementations also have "uninterned symbols", which defeat2976write/read invariance even in implementations with slashification,2977and also generate exceptions to the rule that two symbols are the2978same if and only if their names are spelled the same.29792980<procedure>(symbol? obj)</procedure><br>29812982Returns #t if obj is a symbol, otherwise returns #f.29832984 (symbol? 'foo) ===> #t2985 (symbol? (car '(a b))) ===> #t2986 (symbol? "bar") ===> #f2987 (symbol? 'nil) ===> #t2988 (symbol? '()) ===> #f2989 (symbol? #f) ===> #f29902991<procedure>(symbol=? symbol[1] symbol[2] symbol[3] ...)</procedure>29922993Returns #t if all the arguments all have the same names in the sense of {{string=?}}.29942995Note: The definition above assumes that none of the arguments are uninterned symbols.29962997<procedure>(symbol->string symbol)</procedure><br>29982999Returns the name of symbol as a string. If the symbol was part of an3000object returned as the value of a literal expression (see3001"[[#literal-expressions|literal expressions]]") or by a call to the3002read procedure, and its name contains alphabetic characters, then the3003string returned will contain characters in the implementation's3004preferred standard case -- some implementations will prefer upper3005case, others lower case. If the symbol was returned by string->symbol,3006the case of characters in the string returned will be the same as the3007case in the string that was passed to string->symbol. It is an error3008to apply mutation procedures like string-set! to strings returned by3009this procedure.30103011The following examples assume that the implementation's standard case3012is lower case:30133014 (symbol->string 'flying-fish)3015 ===> "flying-fish"3016 (symbol->string 'Martin) ===> "martin"3017 (symbol->string3018 (string->symbol "Malvina"))3019 ===> "Malvina"30203021<procedure>(string->symbol string)</procedure><br>30223023Returns the symbol whose name is string. This procedure can create3024symbols with names containing special characters or letters in the3025non-standard case, but it is usually a bad idea to create such symbols3026because in some implementations of Scheme they cannot be read as3027themselves. See symbol->string.30283029The following examples assume that the implementation's standard case3030is lower case:30313032 (eq? 'mISSISSIppi 'mississippi)3033 ===> #t3034 (string->symbol "mISSISSIppi")3035 ===> the symbol with name "mISSISSIppi"3036 (eq? 'bitBlt (string->symbol "bitBlt"))3037 ===> #f3038 (eq? 'JollyWog3039 (string->symbol3040 (symbol->string 'JollyWog)))3041 ===> #t3042 (string=? "K. Harper, M.D."3043 (symbol->string3044 (string->symbol "K. Harper, M.D.")))3045 ===> #t30463047==== Characters30483049Characters are objects that represent printed characters such as3050letters and digits. Characters are written using the notation #\3051<character> or #\<character name>. For example:30523053Characters are written using the notation {{#\<character>}} or {{#\<character name>}}3054or {{#\x<hex scalar value>}}.30553056The following character names must be supported by all implementations with the3057given values. Implementations may add other names provided they cannot be3058interpreted as hex scalar values preceded by x.30593060 #\alarm ; U+00073061 #\backspace ; U+00083062 #\delete ; U+007F3063 #\escape ; U+001B3064 #\newline ; the linefeed character, U+000A3065 #\null ; the null character, U+00003066 #\return ; the return character, U+000D3067 #\space ; the preferred way to write a space3068 #\tab ; the tab character, U+000930693070Here are some additional examples:30713072 #\a ; lower case letter3073 #\A ; upper case letter3074 #\( ; left parenthesis3075 #\ ; the space character3076 #\space ; the preferred way to write a space3077 #\newline ; the newline character30783079Case is significant in #\<character>, but not in #\<character name>. If3080<character> in #\<character> is alphabetic, then the character3081following <character> must be a delimiter character such as a space or3082parenthesis. This rule resolves the ambiguous case where, for example,3083the sequence of characters "#\space" could be taken to be either a3084representation of the space character or a representation of the3085character "#\s" followed by a representation of the symbol "pace."30863087Characters written in the #\ notation are self-evaluating. That is,3088they do not have to be quoted in programs. Some of the procedures that3089operate on characters ignore the difference between upper case and3090lower case. The procedures that ignore case have "-ci" (for "case3091insensitive") embedded in their names.30923093<procedure>(char? obj)</procedure><br>30943095Returns #t if obj is a character, otherwise returns #f.30963097<procedure>(char=? char[1] char[2] char[3] ...)</procedure><br>3098<procedure>(char<? char[1] char[2] char[3] ...)</procedure><br>3099<procedure>(char>? char[1] char[2] char[3] ...)</procedure><br>3100<procedure>(char<=? char[1] char[2] char[3] ...)</procedure><br>3101<procedure>(char>=? char[1] char[2] char[3] ...)</procedure><br>31023103These procedures impose a total ordering on the set of characters. It3104is guaranteed that under this ordering:31053106* The upper case characters are in order. For example, (char<? #\A #\3107 B) returns #t.3108* The lower case characters are in order. For example, (char<? #\a #\3109 b) returns #t.3110* The digits are in order. For example, (char<? #\0 #\9) returns #t.3111* Either all the digits precede all the upper case letters, or vice3112 versa.3113* Either all the digits precede all the lower case letters, or vice3114 versa.31153116Some implementations may generalize these procedures to take more than3117two arguments, as with the corresponding numerical predicates.31183119<procedure>(char-ci=? char[1] char[2] char[3] ...)</procedure><br>3120<procedure>(char-ci<? char[1] char[2] char[3] ...)</procedure><br>3121<procedure>(char-ci>? char[1] char[2] char[3] ...)</procedure><br>3122<procedure>(char-ci<=? char[1] char[2] char[3] ...)</procedure><br>3123<procedure>(char-ci>=? char[1] char[2] char[3] ...)</procedure><br>31243125These procedures are similar to char=? et cetera, but they treat upper3126case and lower case letters as the same. For example, (char-ci=? #\A #\3127a) returns #t. Some implementations may generalize these procedures to3128take more than two arguments, as with the corresponding numerical3129predicates.31303131<procedure>(char-alphabetic? char)</procedure><br>3132<procedure>(char-numeric? char)</procedure><br>3133<procedure>(char-whitespace? char)</procedure><br>3134<procedure>(char-upper-case? letter)</procedure><br>3135<procedure>(char-lower-case? letter)</procedure><br>31363137These procedures return #t if their arguments are alphabetic, numeric,3138whitespace, upper case, or lower case characters, respectively,3139otherwise they return #f. The following remarks, which are specific to3140the ASCII character set, are intended only as a guide: The alphabetic3141characters are the 52 upper and lower case letters. The numeric3142characters are the ten decimal digits. The whitespace characters are3143space, tab, line feed, form feed, and carriage return.31443145<procedure>(char->integer char)</procedure><br>3146<procedure>(integer->char n)</procedure><br>31473148Given a character, char->integer returns an exact integer3149representation of the character. Given an exact integer that is the3150image of a character under char->integer, integer->char returns that3151character. These procedures implement order-preserving isomorphisms3152between the set of characters under the char<=? ordering and some3153subset of the integers under the <= ordering. That is, if31543155 (char<=? a b) ===> #t and (<= x y) ===> #t31563157and x and y are in the domain of integer->char, then31583159 (<= (char->integer a)3160 (char->integer b)) ===> #t31613162 (char<=? (integer->char x)3163 (integer->char y)) ===> #t31643165Note that {{integer->char}} does currently not detect3166a negative argument and will quietly convert {{-1}} to3167{{#x1ffff}} in CHICKEN.31683169==== Strings31703171Strings are sequences of characters. Strings are written as sequences of3172characters enclosed within quotation marks ("). Within a string literal,3173various escape sequences represent characters other than themselves. Escape3174sequences always start with a backslash (\):31753176* \a : alarm, U+000731773178* \b : backspace, U+000831793180* \t : character tabulation, U+000931813182* \n : linefeed, U+000A31833184* \r : return, U+000D31853186* \" : double quote, U+002231873188* \\ : backslash, U+005C31893190* \| : vertical line, U+007C31913192* \<intraline whitespace>*<line ending> <intraline whitespace>* : nothing31933194* \x<hex scalar value>; : specified character (note the terminating3195 semi-colon).31963197The result is unspecified if any other character in a string occurs after a3198backslash.31993200Except for a line ending, any character outside of an escape sequence stands3201for itself in the string literal. A line ending which is preceded by \3202<intraline whitespace> expands to nothing (along with any trailing intraline3203whitespace), and can be used to indent strings for improved legibility. Any3204other line ending has the same effect as inserting a \n character into the3205string.32063207Examples:32083209 "The word \"recursion\" has many meanings."3210 "Another example:\ntwo lines of text"3211 "Here's text \3212 containing just one line"3213 "\x03B1; is named GREEK SMALL LETTER ALPHA."32143215The length of a string is the3216number of characters that it contains. This number is an exact, non-negative3217integer that is fixed when the string is created. The valid indexes of a string3218are the exact non-negative integers less than the length of the string. The3219first character of a string has index 0, the second has index 1, and so on.32203221<procedure>(string? obj)</procedure><br>32223223Returns #t if obj is a string, otherwise returns #f.32243225<procedure>(make-string k)</procedure><br>3226<procedure>(make-string k char)</procedure><br>32273228Make-string returns a newly allocated string of length k. If char is3229given, then all elements of the string are initialized to char,3230otherwise the contents of the string are unspecified.32313232<procedure>(string char ...)</procedure><br>32333234Returns a newly allocated string composed of the arguments.32353236<procedure>(string-length string)</procedure><br>32373238Returns the number of characters in the given string.32393240<procedure>(string-ref string k)</procedure><br>32413242k must be a valid index of string. String-ref returns character k of3243string using zero-origin indexing.32443245<procedure>(string-set! string k char)</procedure><br>32463247k must be a valid index of string. String-set! stores char in element k3248of string and returns an unspecified value.32493250 (define (f) (make-string 3 #\*))3251 (define (g) "***")3252 (string-set! (f) 0 #\?) ===> unspecified3253 (string-set! (g) 0 #\?) ===> error3254 (string-set! (symbol->string 'immutable)3255 03256 #\?) ===> error32573258<procedure>(string=? string[1] string[2] string[3] ...)</procedure><br>32593260Returns #t if the two strings are the same length and contain the same3261characters in the same positions, otherwise returns #f.32623263<procedure>(string<? string[1] string[2] string[3] ...)</procedure><br>3264<procedure>(string>? string[1] string[2] string[3] ...)</procedure><br>3265<procedure>(string<=? string[1] string[2] string[3] ...)</procedure><br>3266<procedure>(string>=? string[1] string[2] string[3] ...)</procedure><br>32673268These procedures are the lexicographic extensions to strings of the3269corresponding orderings on characters. For example, string<? is the3270lexicographic ordering on strings induced by the ordering char<? on3271characters. If two strings differ in length but are the same up to the3272length of the shorter string, the shorter string is considered to be3273lexicographically less than the longer string.32743275<procedure>(substring string start [end])</procedure><br>32763277String must be a string, and start and end must be exact integers3278satisfying32793280 0 <= start <= end <= (string-length string)32813282Substring returns a newly allocated string formed from the characters3283of string beginning with index start (inclusive) and ending with index3284end (exclusive). The {{end}} argument is optional and defaults to the3285length of the string, this is a non-standard extension in CHICKEN.32863287<procedure>(string-append string ...)</procedure><br>32883289Returns a newly allocated string whose characters form the3290concatenation of the given strings.32913292<procedure>(string->list string [start [end]])</procedure><br>3293<procedure>(list->string list)</procedure><br>32943295String->list returns a newly allocated list of the characters that make3296up the given string between start and end. List->string returns a newly allocated string3297formed from the characters in the list list, which must be a list of3298characters. String->list and list->string are inverses so far as equal?3299is concerned.33003301<procedure>(string-copy string [start [end]])</procedure><br>33023303Returns a newly allocated copy of the given string.33043305<procedure>(string-copy! to at from [start [end]])</procedure>33063307It is an error if at is less than zero or greater than the length of to. It is also an error if {{(- (string-length to) at)}} is less than {{(- end start)}}.33083309Copies the characters of string from between start and end to string to, starting at3310at. The order in which characters are copied is unspecified, except that if the3311source and destination overlap, copying takes place as if the source is first3312copied into a temporary string and then into the destination. This can be3313achieved without allocating storage by making sure to copy in the correct3314direction in such circumstances.33153316 (define a "12345")3317 (define b (string-copy "abcde"))3318 (string-copy! b 1 a 0 2)3319 b ==> "a12de"33203321<procedure>(string-fill! string char +#!optional start end)</procedure><br>33223323Stores char in every element of the given string and returns an3324unspecified value. The optional start and end arguments specify3325the part of the string to be filled and default to the complete string.33263327==== Vectors33283329Vectors are heterogenous structures whose elements are indexed by3330integers. A vector typically occupies less space than a list of the3331same length, and the average time required to access a randomly chosen3332element is typically less for the vector than for the list.33333334The length of a vector is the number of elements that it contains. This3335number is a non-negative integer that is fixed when the vector is3336created. The valid indexes of a vector are the exact non-negative3337integers less than the length of the vector. The first element in a3338vector is indexed by zero, and the last element is indexed by one less3339than the length of the vector.33403341Vectors are written using the notation #(obj ...). For example, a3342vector of length 3 containing the number zero in element 0, the list (233432 2 2) in element 1, and the string "Anna" in element 2 can be written3344as following:33453346 #(0 (2 2 2 2) "Anna")33473348Vector constants are self-evaluating, so they do not need3349to be quoted in programs.33503351<procedure>(vector? obj)</procedure><br>33523353Returns #t if obj is a vector, otherwise returns #f.33543355<procedure>(make-vector k)</procedure><br>3356<procedure>(make-vector k fill)</procedure><br>33573358Returns a newly allocated vector of k elements. If a second argument is3359given, then each element is initialized to fill. Otherwise the initial3360contents of each element is unspecified.33613362<procedure>(vector obj ...)</procedure><br>33633364Returns a newly allocated vector whose elements contain the given3365arguments. Analogous to list.33663367 (vector 'a 'b 'c) ===> #(a b c)33683369<procedure>(vector-length vector)</procedure><br>33703371Returns the number of elements in vector as an exact integer.33723373<procedure>(vector-ref vector k)</procedure><br>33743375k must be a valid index of vector. Vector-ref returns the contents of3376element k of vector.33773378 (vector-ref '#(1 1 2 3 5 8 13 21)3379 5)3380 ===> 83381 (vector-ref '#(1 1 2 3 5 8 13 21)3382 (let ((i (round (* 2 (acos -1)))))3383 (if (inexact? i)3384 (inexact->exact i)3385 i)))3386 ===> 1333873388<procedure>(vector-set! vector k obj)</procedure><br>33893390k must be a valid index of vector. Vector-set! stores obj in element k3391of vector. The value returned by vector-set! is unspecified.33923393 (let ((vec (vector 0 '(2 2 2 2) "Anna")))3394 (vector-set! vec 1 '("Sue" "Sue"))3395 vec)3396 ===> #(0 ("Sue" "Sue") "Anna")33973398 (vector-set! '#(0 1 2) 1 "doe")3399 ===> error ; constant vector34003401<procedure>(vector->list vector [start [end]])</procedure><br>3402<procedure>(list->vector list)</procedure><br>34033404Vector->list returns a newly allocated list of the objects contained in3405the elements of vector. List->vector returns a newly created vector3406initialized to the elements of the list list.34073408 (vector->list '#(dah dah didah))3409 ===> (dah dah didah)3410 (list->vector '(dididit dah))3411 ===> #(dididit dah)34123413<procedure>(vector->string vector [start [end]])</procedure><br>3414<procedure>(string->vector string [start [end]])</procedure>34153416It is an error if any element of vector between start and end is not a character.34173418The vector->string procedure returns a newly allocated string of the objects3419contained in the elements of vector between start and end. The string->vector procedure returns a newly created vector initialized to3420the elements of the string string between start and end.34213422In both procedures, order is preserved.34233424 (string->vector "ABC") ==> #(#\A #\B #\C)3425 (vector->string #(#\1 #\2 #\3)) ==> "123"34263427<procedure>(vector-copy vector [start [end]])</procedure>34283429Returns a newly allocated copy of the elements of the given vector between3430start and end. The elements of the new vector are the same (in the sense of eqv?) as the3431elements of the old.34323433 (define a #(1 8 2 8)) ; a may be immutable3434 (define b (vector-copy a))3435 (vector-set! b 0 3) ; b is mutable3436 b ==> #(3 8 2 8)3437 (define c (vector-copy b 1 3))3438 c ==> #(8 2)34393440<procedure>(vector-copy! to at from [start [end]])</procedure>34413442It is an error if at is less than zero or greater than the length of to. It is also an error if {{(- (vector-length to) at)}} is less than {{(- end start)}}.34433444Copies the elements of vector from between start and end to vector to, starting at3445at. The order in which elements are copied is unspecified, except that if the3446source and destination overlap, copying takes place as if the source is first3447copied into a temporary vector and then into the destination. This can be3448achieved without allocating storage by making sure to copy in the correct3449direction in such circumstances.34503451 (define a (vector 1 2 3 4 5))3452 (define b (vector 10 20 30 40 50))3453 (vector-copy! b 1 a 0 2)3454 b ==> #(10 1 2 40 50)34553456<procedure>(vector-append vector ....)</procedure>34573458Returns a newly allocated vector whose elements are the concatenation of the3459elements of the given vectors.34603461 (vector-append #(a b c) #(d e f)) ==> #(a b c d e f)34623463<procedure>(vector-fill! vector fill [start [end]])</procedure>34643465The vector-fill! procedure stores fill in the elements of vector between start and3466end.34673468 (define a (vector 1 2 3 4 5))3469 (vector-fill! a 'smash 2 4)3470 a ==>#(1 2 smash smash 5)34713472==== Bytevectors34733474Bytevectors represent blocks of binary data. They are fixed-length sequences of3475bytes, where a byte is an exact integer in the range from 0 to 255 inclusive. A3476bytevector is typically more space-efficient than a vector containing the same3477values.34783479See [[Module (chicken bytevector)|The (chicken bytevector) module]] for more3480information. {{(scheme base)}} re-exports all R7RS-specific procedures from3481that module.34823483=== Control features34843485This chapter describes various primitive procedures which control the3486flow of program execution in special ways. The procedure? predicate is3487also described here.34883489<procedure>(procedure? obj)</procedure><br>34903491Returns #t if obj is a procedure, otherwise returns #f.34923493 (procedure? car) ===> #t3494 (procedure? 'car) ===> #f3495 (procedure? (lambda (x) (* x x)))3496 ===> #t3497 (procedure? '(lambda (x) (* x x)))3498 ===> #f3499 (call-with-current-continuation procedure?)3500 ===> #t35013502<procedure>(apply proc arg[1] ... args)</procedure><br>35033504Proc must be a procedure and args must be a list. Calls proc with the3505elements of the list (append (list arg[1] ...) args) as the actual3506arguments.35073508 (apply + (list 3 4)) ===> 735093510 (define compose3511 (lambda (f g)3512 (lambda args3513 (f (apply g args)))))35143515 ((compose sqrt *) 12 75) ===> 3035163517<procedure>(map proc list[1] list[2] ...)</procedure><br>35183519The lists must be lists, and proc must be a procedure taking as many3520arguments as there are lists and returning a single value. Map applies3521proc element-wise to the elements of the lists and returns a list of3522the results, in order. The dynamic order in which proc is applied to3523the elements of the lists is unspecified.35243525Like in SRFI-1, this procedure allows the arguments to be of unequal3526length; it terminates when the shortest list runs out. This is a3527CHICKEN extension to R7RS.35283529 (map cadr '((a b) (d e) (g h)))3530 ===> (b e h)35313532 (map (lambda (n) (expt n n))3533 '(1 2 3 4 5))3534 ===> (1 4 27 256 3125)35353536 (map + '(1 2 3) '(4 5 6)) ===> (5 7 9)35373538 (let ((count 0))3539 (map (lambda (ignored)3540 (set! count (+ count 1))3541 count)3542 '(a b))) ===> (1 2) or (2 1)35433544<procedure>(string-map proc string[1] string[2] ...)</procedure>35453546It is an error if proc does not accept as many arguments as there are strings and return a single character.35473548The string-map procedure applies proc element-wise to the elements of the3549strings and returns a string of the results, in order. If more than one3550string is given and not all strings have the same length, string-map terminates3551when the shortest string runs out. The dynamic order in which3552proc is applied to the elements of the3553strings is unspecified. If multiple returns occur from string-map, the values3554returned by earlier returns are not mutated.35553556 (string-map char-foldcase "AbdEgH") ==> "abdegh"35573558 (string-map3559 (lambda (c)3560 (integer->char (+ 1 (char->integer c))))3561 "HAL") ==> "IBM"35623563 (string-map3564 (lambda (c k)3565 ((if (eqv? k #\u) char-upcase char-downcase)3566 c))3567 "studlycaps xxx"3568 "ululululul") ==> "StUdLyCaPs"35693570<procedure>(vector-map proc vector[1] vector[2] ...)</procedure>35713572It is an error if proc does not accept as many arguments as there are vectors and return a single value.35733574The vector-map procedure applies proc element-wise to the elements of the3575vectors and returns a vector of the results, in order. If more than one3576vector is given and not all vectors have the same length, vector-map terminates3577when the shortest vector runs out. The dynamic order in which3578proc is applied to the elements of the3579vectors is unspecified. If multiple returns occur from vector-map, the values3580returned by earlier returns are not mutated.35813582 (vector-map cadr '#((a b) (d e) (g h)))3583 ==> #(b e h)35843585 (vector-map (lambda (n) (expt n n))3586 '#(1 2 3 4 5))3587 ==> #(1 4 27 256 3125)35883589 (vector-map + '#(1 2 3) '#(4 5 6 7))3590 ==> #(5 7 9)35913592 (let ((count 0))3593 (vector-map3594 (lambda (ignored)3595 (set! count (+ count 1))3596 count)3597 '#(a b))) ==> #(1 2) or #(2 1)35983599<procedure>(for-each proc list[1] list[2] ...)</procedure><br>36003601The arguments to for-each are like the arguments to map, but for-each3602calls proc for its side effects rather than for its values. Unlike map,3603for-each is guaranteed to call proc on the elements of the lists in3604order from the first element(s) to the last, and the value returned by3605for-each is unspecified.36063607 (let ((v (make-vector 5)))3608 (for-each (lambda (i)3609 (vector-set! v i (* i i)))3610 '(0 1 2 3 4))3611 v) ===> #(0 1 4 9 16)36123613Like in SRFI-1, this procedure allows the arguments to be of unequal3614length; it terminates when the shortest list runs out. This is a3615CHICKEN extension to R7RS.36163617<procedure>(string-for-each proc string[1] string[2] ...)</procedure>36183619It is an error if proc does not accept as many arguments as there are strings.3620The arguments to string-for-each are like the arguments to string-map, but3621string-for-each calls3622proc for its side effects rather than for its values. Unlike string-map,3623string-for-each is guaranteed to call3624proc on the elements of the3625strings in order from the first element(s) to the last, and the value returned3626by string-for-each is unspecified. If more than one3627string is given and not all strings have the same length, string-for-each3628terminates when the shortest string runs out. It is an error for3629proc to mutate any of the strings.36303631 (let ((v '()))3632 (string-for-each3633 (lambda (c) (set! v (cons (char->integer c) v)))3634 "abcde")3635 v) ==> (101 100 99 98 97)36363637<procedure>(vector-for-each proc vector[1] vector[2] ...)</procedure>36383639It is an error if proc does not accept as many arguments as there are vectors.3640The arguments to vector-for-each are like the arguments to vector-map, but3641vector-for-each calls3642proc for its side effects rather than for its values. Unlike vector-map,3643vector-for-each is guaranteed to call3644proc on the elements of the3645vectors in order from the first element(s) to the last, and the value returned3646by vector-for-each is unspecified. If more than one3647vector is given and not all vectors have the same length, vector-for-each3648terminates when the shortest vector runs out. It is an error for3649proc to mutate any of the vectors.36503651 (let ((v (make-list 5)))3652 (vector-for-each3653 (lambda (i) (list-set! v i (* i i)))3654 '#(0 1 2 3 4))3655 v) ==> (0 1 4 9 16)36563657<procedure>(call-with-current-continuation proc)</procedure><br>3658<procedure>(call/cc proc)</procedure><br>36593660Proc must be a procedure of one argument. The procedure3661call-with-current-continuation packages up the current continuation3662(see the rationale below) as an "escape procedure" and passes it as3663an argument to proc. The escape procedure is a Scheme procedure that,3664if it is later called, will abandon whatever continuation is in effect3665at that later time and will instead use the continuation that was in3666effect when the escape procedure was created. Calling the escape3667procedure may cause the invocation of before and after thunks installed3668using dynamic-wind.36693670The escape procedure accepts the same number of arguments as the3671continuation to the original call to call-with-current-continuation.3672Except for continuations created by the call-with-values procedure, all3673continuations take exactly one value. The effect of passing no value or3674more than one value to continuations that were not created by3675call-with-values is unspecified.36763677The escape procedure that is passed to proc has unlimited extent just3678like any other procedure in Scheme. It may be stored in variables or3679data structures and may be called as many times as desired.36803681The following examples show only the most common ways in which3682call-with-current-continuation is used. If all real uses were as simple3683as these examples, there would be no need for a procedure with the3684power of call-with-current-continuation.36853686 (call-with-current-continuation3687 (lambda (exit)3688 (for-each (lambda (x)3689 (if (negative? x)3690 (exit x)))3691 '(54 0 37 -3 245 19))3692 #t)) ===> -336933694 (define list-length3695 (lambda (obj)3696 (call-with-current-continuation3697 (lambda (return)3698 (letrec ((r3699 (lambda (obj)3700 (cond ((null? obj) 0)3701 ((pair? obj)3702 (+ (r (cdr obj)) 1))3703 (else (return #f))))))3704 (r obj))))))37053706 (list-length '(1 2 3 4)) ===> 437073708 (list-length '(a b . c)) ===> #f37093710Rationale:37113712A common use of call-with-current-continuation is for structured,3713non-local exits from loops or procedure bodies, but in fact3714call-with-current-continuation is extremely useful for implementing3715a wide variety of advanced control structures.37163717Whenever a Scheme expression is evaluated there is a continuation3718wanting the result of the expression. The continuation represents3719an entire (default) future for the computation. If the expression3720is evaluated at top level, for example, then the continuation might3721take the result, print it on the screen, prompt for the next input,3722evaluate it, and so on forever. Most of the time the continuation3723includes actions specified by user code, as in a continuation that3724will take the result, multiply it by the value stored in a local3725variable, add seven, and give the answer to the top level3726continuation to be printed. Normally these ubiquitous continuations3727are hidden behind the scenes and programmers do not think much3728about them. On rare occasions, however, a programmer may need to3729deal with continuations explicitly. Call-with-current-continuation3730allows Scheme programmers to do that by creating a procedure that3731acts just like the current continuation.37323733Most programming languages incorporate one or more special-purpose3734escape constructs with names like exit, return, or even goto. In37351965, however, Peter Landin [16] invented a general purpose escape3736operator called the J-operator. John Reynolds [24] described a3737simpler but equally powerful construct in 1972. The catch special3738form described by Sussman and Steele in the 1975 report on Scheme3739is exactly the same as Reynolds's construct, though its name came3740from a less general construct in MacLisp. Several Scheme3741implementors noticed that the full power of the catch construct3742could be provided by a procedure instead of by a special syntactic3743construct, and the name call-with-current-continuation was coined3744in 1982. This name is descriptive, but opinions differ on the3745merits of such a long name, and some people use the name call/cc3746instead.37473748<procedure>(values obj ...)</procedure><br>37493750Delivers all of its arguments to its continuation. Except for3751continuations created by the call-with-values procedure, all3752continuations take exactly one value. Values might be defined as3753follows:37543755 (define (values . things)3756 (call-with-current-continuation3757 (lambda (cont) (apply cont things))))37583759<procedure>(call-with-values producer consumer)</procedure><br>37603761Calls its producer argument with no values and a continuation that,3762when passed some values, calls the consumer procedure with those values3763as arguments. The continuation for the call to consumer is the3764continuation of the call to call-with-values.37653766 (call-with-values (lambda () (values 4 5))3767 (lambda (a b) b))3768 ===> 537693770 (call-with-values * -) ===> -137713772<procedure>(dynamic-wind before thunk after)</procedure><br>37733774Calls thunk without arguments, returning the result(s) of this call.3775Before and after are called, also without arguments, as required by the3776following rules (note that in the absence of calls to continuations3777captured using call-with-current-continuation the three arguments are3778called once each, in order). Before is called whenever execution enters3779the dynamic extent of the call to thunk and after is called whenever it3780exits that dynamic extent. The dynamic extent of a procedure call is3781the period between when the call is initiated and when it returns. In3782Scheme, because of call-with-current-continuation, the dynamic extent3783of a call may not be a single, connected time period. It is defined as3784follows:37853786* The dynamic extent is entered when execution of the body of the3787 called procedure begins.37883789* The dynamic extent is also entered when execution is not within the3790 dynamic extent and a continuation is invoked that was captured3791 (using call-with-current-continuation) during the dynamic extent.37923793* It is exited when the called procedure returns.37943795* It is also exited when execution is within the dynamic extent and a3796 continuation is invoked that was captured while not within the3797 dynamic extent.37983799If a second call to dynamic-wind occurs within the dynamic extent of3800the call to thunk and then a continuation is invoked in such a way that3801the afters from these two invocations of dynamic-wind are both to be3802called, then the after associated with the second (inner) call to3803dynamic-wind is called first.38043805If a second call to dynamic-wind occurs within the dynamic extent of3806the call to thunk and then a continuation is invoked in such a way that3807the befores from these two invocations of dynamic-wind are both to be3808called, then the before associated with the first (outer) call to3809dynamic-wind is called first.38103811If invoking a continuation requires calling the before from one call to3812dynamic-wind and the after from another, then the after is called3813first.38143815The effect of using a captured continuation to enter or exit the3816dynamic extent of a call to before or after is undefined. However,3817in CHICKEN it is safe to do this, and they will execute in the outer3818dynamic context of the {{dynamic-wind}} form.38193820 (let ((path '())3821 (c #f))3822 (let ((add (lambda (s)3823 (set! path (cons s path)))))3824 (dynamic-wind3825 (lambda () (add 'connect))3826 (lambda ()3827 (add (call-with-current-continuation3828 (lambda (c0)3829 (set! c c0)3830 'talk1))))3831 (lambda () (add 'disconnect)))3832 (if (< (length path) 4)3833 (c 'talk2)3834 (reverse path))))38353836 ===> (connect talk1 disconnect3837 connect talk2 disconnect)38383839=== Exceptions38403841This section describes Scheme's exception-handling and exception-raising3842procedures.38433844Exception handlers are one-argument procedures that determine the action the3845program takes when an exceptional situation is signaled. The system implicitly3846maintains a current exception handler in the dynamic environment.38473848The program raises an exception by invoking the current exception handler,3849passing it an object encapsulating information about the exception. Any3850procedure accepting one argument can serve as an exception handler and any3851object can be used to represent an exception.38523853<procedure>(with-exception-handler handler thunk)</procedure>38543855It is an error if handler does not accept one argument. It is also an error if3856thunk does not accept zero arguments.3857The with-exception-handler procedure returns the results of invoking3858thunk.3859Handler is installed as the current exception handler in the dynamic3860environment used for the invocation of3861thunk.38623863 (call-with-current-continuation3864 (lambda (k)3865 (with-exception-handler3866 (lambda (x)3867 (display "condition: ")3868 (write x)3869 (newline)3870 (k 'exception))3871 (lambda ()3872 (+ 1 (raise 'an-error))))))3873 ==> exception and prints "condition: an-error"38743875 (with-exception-handler3876 (lambda (x)3877 (display "something went wrong\n"))3878 (lambda ()3879 (+ 1 (raise 'an-error))))38803881prints "something went wrong"3882After printing, the second example then raises another exception.38833884<procedure>(raise obj)</procedure>38853886Raises an exception by invoking the current exception handler on3887obj. The handler is called with the same dynamic environment as that of the3888call to raise, except that the current exception handler is the one that was in3889place when the handler being called was installed. If the handler returns, a3890secondary exception is raised in the same dynamic environment as the handler.3891The relationship between3892obj and the object raised by the secondary exception is unspecified.38933894<procedure>(raise-continuable obj)</procedure>38953896Raises an exception by invoking the current exception handler on3897obj. The handler is called with the same dynamic environment as the call to3898raise-continuable, except that: (1) the current exception handler is the one3899that was in place when the handler being called was installed, and (2) if the3900handler being called returns, then it will again become the current exception3901handler. If the handler returns, the values it returns become the values3902returned by the call to raise-continuable.39033904 (with-exception-handler3905 (lambda (con)3906 (cond3907 ((string? con)3908 (display con))3909 (else3910 (display "a warning has been issued")))3911 42)3912 (lambda ()3913 (+ (raise-continuable "should be a number")3914 23)))3915 prints: "should be a number"3916 ==> 6539173918<procedure>(error [location] message obj ...)</procedure>39193920Message should be a string.3921Raises an exception as if by calling raise on a newly allocated3922implementation-defined object which encapsulates the information provided by3923message, as well as any3924objs, known as the irritants. The procedure error-object? must return #t on3925such objects.39263927 (define (null-list? l)3928 (cond ((pair? l) #f)3929 ((null? l) #t)3930 (else3931 (error3932 "null-list?: argument out of domain"3933 l))))39343935If location is given and a symbol, it indicates the name of the procedure where3936the error occurred.39373938<procedure>(error-object? obj)</procedure>39393940Returns #t if3941obj is an object created by error or one of an implementation-defined set of3942objects. Otherwise, it returns #f. The objects used to signal errors, including3943those which satisfy the predicates file-error? and read-error?, may or may not3944satisfy error-object?.39453946<procedure>(error-object-message error-object)</procedure>39473948Returns the message encapsulated by3949error-object.39503951<procedure>(error-object-irritants error-object)</procedure>39523953Returns a list of the irritants encapsulated by3954error-object.39553956<procedure>(read-error? obj)</procedure><br>3957<procedure>(file-error? obj)</procedure>39583959Error type predicates. Returns #t if3960obj is an object raised by the read procedure or by the inability to open an3961input or output port on a file, respectively. Otherwise, it returns #f.39623963=== Eval39643965<procedure>(eval expression [environment-specifier])</procedure><br>39663967Evaluates expression in the specified environment and returns its3968value. Expression must be a valid Scheme expression represented as3969data, and environment-specifier must be a value returned by one of the3970three procedures described below. Implementations may extend eval to3971allow non-expression programs (definitions) as the first argument and3972to allow other values as environments, with the restriction that eval3973is not allowed to create new bindings in the environments associated3974with null-environment or scheme-report-environment.39753976 (eval '(* 7 3) (scheme-report-environment 5))3977 ===> 2139783979 (let ((f (eval '(lambda (f x) (f x x))3980 (null-environment 5))))3981 (f + 10))3982 ===> 2039833984The {{environment-specifier}} is optional, and if not provided it3985defaults to the value of {{(interaction-environment)}}. This is a3986CHICKEN extension to R7RS, which, though strictly nonportable, is very3987common among Scheme implementations.39883989=== Input and output39903991==== Ports39923993Ports represent input and output devices. To Scheme, an input port is a Scheme3994object that can deliver data upon command, while an output port is a Scheme3995object that can accept data.39963997Different port types operate on different data. Scheme implementations are3998required to support textual ports and binary ports, but may also provide other3999port types.40004001A textual port supports reading or writing of individual characters from or to4002a backing store containing characters using read-char and write-char below, and4003it supports operations defined in terms of characters, such as read and write.40044005A binary port supports reading or writing of individual bytes from or to a4006backing store containing bytes using read-u8 and write-u8 below, as well as4007operations defined in terms of bytes. Whether the textual and binary port types4008are disjoint is implementation-dependent.40094010Ports can be used to access files, devices, and similar things on the host4011system on which the Scheme program is running.40124013<procedure>(call-with-port port proc)</procedure>40144015It is an error if4016proc does not accept one argument.4017The call-with-port procedure calls4018proc with4019port as an argument. If4020proc returns, then the port is closed automatically and the values yielded by4021the4022proc are returned. If40234024proc does not return, then the port must not be closed automatically unless it4025is possible to prove that the port will never again be used for a read or write4026operation.40274028 Rationale: Because Scheme's escape procedures have unlimited extent, it is4029 possible to escape from the current continuation but later to resume it. If4030 implementations were permitted to close the port on any escape from the4031 current continuation, then it would be impossible to write portable code4032 using both call-with-current-continuation and call-with-port.40334034Ports represent input and output devices. To Scheme, an input port is a4035Scheme object that can deliver characters upon command, while an output4036port is a Scheme object that can accept characters.40374038<procedure>(input-port? obj)</procedure><br>4039<procedure>(output-port? obj)</procedure><br>4040<procedure>(textual-port? obj)</procedure><br>4041<procedure>(binary-port? obj)</procedure><br>4042<procedure>(port? obj)</procedure>40434044These procedures return #t if4045obj is an input port, output port, textual port, binary port, or any kind of4046port, respectively. Otherwise they return #f.40474048<procedure>(input-port-open? port)</procedure><br>4049<procedure>(output-port-open? port)</procedure>40504051Returns #t if4052port is still open and capable of performing input or output, respectively, and4053#f otherwise.40544055<procedure>(current-input-port [port])</procedure><br>4056<procedure>(current-output-port [port])</procedure><br>4057<procedure>(current-error-port [port])</procedure><br>40584059Returns the current default input, output or error port.40604061If the optional {{port}} argument is passed, the current input or4062output port is changed to the provided port. It can also be used with4063{{parameterize}} to temporarily bind the port to another value. This4064is a CHICKEN extension to the R7RS standard.40654066Note that the default output port is not buffered. Use4067[[Module (chicken port)#set-buffering-mode!|{{set-buffering-mode!}}]]4068if you need a different behavior.40694070<procedure>(open-input-file filename [mode ...])</procedure><br>4071<procedure>(open-binary-input-file filename [mode ...])</procedure>40724073Takes a string naming an existing file and returns an input port4074capable of delivering textual or binary data from the file. If the file cannot be4075opened, an error is signalled.40764077Additional {{mode}} arguments can be passed in, which should be any of4078the keywords {{#:text}} or {{#:binary}}. These indicate the mode in4079which to open the file (this has an effect on non-UNIX platforms4080only). The extra {{mode}} arguments are CHICKEN extensions to the4081R7RS standard.40824083<procedure>(close-port port)</procedure><br>4084<procedure>(close-input-port port)</procedure><br>4085<procedure>(close-output-port port)</procedure><br>40864087Closes the resource associated with4088port, rendering the4089port incapable of delivering or accepting data. It is an error to apply the4090last two procedures to a port which is not an input or output port,4091respectively. Scheme implementations may provide ports which are simultaneously4092input and output ports, such as sockets; the close-input-port and4093close-output-port procedures can then be used to close the input and output4094sides of the port independently.40954096These routines have no effect if the port has already been closed.40974098<procedure>(open-input-string string)</procedure>40994100Takes a string and returns a textual input port that delivers characters from4101the string. If the string is modified, the effect is unspecified.41024103<procedure>(open-output-string)</procedure>41044105Returns a textual output port that will accumulate characters for retrieval by4106get-output-string.41074108<procedure>(get-output-string port)</procedure>41094110It is an error if4111port was not created with open-output-string.4112Returns a string consisting of the characters that have been output to the port4113so far in the order they were output. If the result string is modified, the4114effect is unspecified.41154116 (parameterize4117 ((current-output-port4118 (open-output-string)))4119 (display "piece")4120 (display " by piece ")4121 (display "by piece.")4122 (newline)4123 (get-output-string (current-output-port)))4124 ==> "piece by piece by piece.\n"41254126<procedure>(open-input-bytevector bytevector)</procedure>41274128Takes a bytevector and returns a binary input port that delivers bytes from the4129bytevector.41304131<procedure>(open-output-bytevector)</procedure>41324133Returns a binary output port that will accumulate bytes for retrieval by4134get-output-bytevector.41354136<procedure>(get-output-bytevector port)</procedure>41374138It is an error if4139port was not created with open-output-bytevector.4140Returns a bytevector consisting of the bytes that have been output to the port4141so far in the order they were output.41424143==== Input41444145If port is omitted from any input procedure, it defaults to the value returned by4146(current-input-port). It is an error to attempt an input operation on a closed4147port.41484149<procedure>(read-char [port])</procedure><br>41504151Returns the next character available from the input port, updating the4152port to point to the following character. If no more characters are4153available, an end of file object is returned. Port may be omitted, in4154which case it defaults to the value returned by current-input-port.41554156<procedure>(peek-char [port])</procedure><br>41574158Returns the next character available from the input port, without4159updating the port to point to the following character. If no more4160characters are available, an end of file object is returned. Port may4161be omitted, in which case it defaults to the value returned by4162current-input-port.41634164Note: The value returned by a call to peek-char is the same as4165the value that would have been returned by a call to read-char with4166the same port. The only difference is that the very next call to4167read-char or peek-char on that port will return the value returned4168by the preceding call to peek-char. In particular, a call to4169peek-char on an interactive port will hang waiting for input4170whenever a call to read-char would have hung.41714172<procedure>(read-line [port])</procedure>41734174Returns the next line of text available from the textual input4175port, updating the4176port to point to the following character. If an end of line is read, a string4177containing all of the text up to (but not including) the end of line is4178returned, and the port is updated to point just past the end of line. If an end4179of file is encountered before any end of line is read, but some characters have4180been read, a string containing those characters is returned. If an end of file4181is encountered before any characters are read, an end-of-file object is4182returned. For the purpose of this procedure, an end of line consists of either4183a linefeed character, a carriage return character, or a sequence of a carriage4184return character followed by a linefeed character. Implementations may also4185recognize other end of line characters or sequences.41864187<procedure>(eof-object? obj)</procedure><br>41884189Returns #t if obj is an end of file object, otherwise returns #f. The4190precise set of end of file objects will vary among implementations, but4191in any case no end of file object will ever be an object that can be4192read in using read.41934194<procedure>(eof-object)</procedure>41954196Returns an end-of-file object, not necessarily unique.41974198<procedure>(char-ready? [port])</procedure><br>41994200Returns #t if a character is ready on the input port and returns #f4201otherwise. If char-ready returns #t then the next read-char operation4202on the given port is guaranteed not to hang. If the port is at end of4203file then char-ready? returns #t. Port may be omitted, in which case it4204defaults to the value returned by current-input-port.42054206Rationale: Char-ready? exists to make it possible for a program4207to accept characters from interactive ports without getting stuck4208waiting for input. Any input editors associated with such ports4209must ensure that characters whose existence has been asserted by4210char-ready? cannot be rubbed out. If char-ready? were to return #f4211at end of file, a port at end of file would be indistinguishable4212from an interactive port that has no ready characters.42134214<procedure>(read-string k [port])</procedure>42154216See [[Module (chicken io)|(chicken io) module]] for more information.42174218<procedure>(read-u8 [port])</procedure>42194220Returns the next byte available from the binary input4221port, updating the4222port to point to the following byte. If no more bytes are available, an4223end-of-file object is returned.42244225<procedure>(peek-u8 [port])</procedure>42264227Returns the next byte available from the binary input4228port, but without updating the4229port to point to the following byte. If no more bytes are available, an4230end-of-file object is returned.42314232<procedure>(u8-ready? [port])</procedure>42334234Returns #t if a byte is ready on the binary input4235port and returns #f otherwise. If u8-ready? returns #t then the next read-u84236operation on the given4237port is guaranteed not to hang. If the4238port is at end of file then u8-ready? returns #t.42394240<procedure>(read-bytevector k [port])</procedure><br>4241<procedure>(read-bytevector! bytevector [port [start [end]]])</procedure>42424243See [[Module (chicken io)|(chicken io) module]] for more information.42444245==== Output42464247If port is omitted from any output procedure, it defaults to the value returned by4248(current-output-port). It is an error to attempt an output operation on a4249closed port.42504251<procedure>(newline)</procedure><br>4252<procedure>(newline port)</procedure><br>42534254Writes an end of line to port. Exactly how this is done differs from4255one operating system to another. Returns an unspecified value. The port4256argument may be omitted, in which case it defaults to the value4257returned by current-output-port.42584259<procedure>(write-char char)</procedure><br>4260<procedure>(write-char char port)</procedure><br>42614262Writes the character char (not an external representation of the4263character) to the given port and returns an unspecified value. The port4264argument may be omitted, in which case it defaults to the value4265returned by current-output-port.42664267<procedure>(write-string string [port [start [end]]])</procedurew>42684269Writes the characters of4270string from4271start to4272end in left-to-right order to the textual output4273port.42744275<procedure>(write-u8 byte [port])</procedure>42764277Writes the4278byte to the given binary output4279port and returns an unspecified value.42804281<procedure>(write-bytevector bytevector [port [start [end]]])</procedure>42824283See [[Module (chicken bytevector)|The (chicken bytevector) module]] for more4284information.42854286<procedure>(flush-output-port [port])</procedure>42874288Flushes any buffered output from the buffer of output-port to the underlying4289file or device and returns an unspecified value.42904291==== System interface42924293Questions of system interface generally fall outside of the domain of4294this report. However, the following operations are important enough to4295deserve description here.42964297<procedure>(features)</procedure>42984299Returns a list of the feature identifiers which cond-expand treats as true. It4300is an error to modify this list. Here is an example of what features might4301return:43024303 (features) ==>4304 (r7rs ratios exact-complex full-unicode4305 gnu-linux little-endian4306 fantastic-scheme4307 fantastic-scheme-1.04308 space-ship-control-system)43094310---4311Previous: [[Module scheme]]43124313Next: [[Module (scheme case-lambda)]]